且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JSON.NET(WebApi2) - 序列化属性,但反序列化过程跳过

更新时间:2023-02-16 15:38:22

据我了解,你想用JSON字符串的所有属性序列化对象,但只提取选定的性能,同时反序列化该字符串。

As I understand you want to serialize object with all properties in json string but retrieve only selected properties while deserialization on that string.

如果这是这样,那么,我就在那里我创建了基本类型和DerivedType类的话,我序列化派生类型为JSON字符串反序列化的同时,我希望它在基本类型实例类似的规定。所以写了这个code:

If this is case then, I had a similar requirement where I created BaseType and DerivedType classes then I serialize derived type into Json string while deserialization I want it in Base type instance. So wrote this code :

    using System.Web.Script.Serialization;

    public static TB CastToBase<T, TB>(this T derivedTypeInstance) 
        {
            var serializer = new JavaScriptSerializer();
            var baseTypeInstance = serializer.Deserialize<TB>(serializer.Serialize(derivedTypeInstance));
            return baseTypeInstance;
        }