JSON.NET (WebApi2) - Serialize property, but skip during deserialization

╄→гoц情女王★ 提交于 2019-12-08 06:23:23

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

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;
        } 

I think you can put [JsonObject(MemberSerialization.OptIn)] property on the class, which requires to explicitly state which properties to serialize. Then you can use both [JsonProperty] and [JsonIgnore] on a property you'd like to serialize as normal but ignore on deserialization.

Example:

    [JsonObject(MemberSerialization.OptIn)]
    private class UserData
    {
        [JsonProperty]      
        public string Token { get; set; }

        [JsonProperty]
        public string Username { get; set; }

        [JsonIgnore]
        [JsonProperty]
        public string Password { get; set; }
    }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!