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

Deadly 提交于 2019-12-23 03:32:24

问题


I know of [JsonIgnore] which ignores properties altogether, I know of ShouldSerializePropertyName which gives conditional serialization, but I cannot find anything to mark property to be serialized into JSON normally, but not set during deserialization.

I could write a workaround:

[JsonIgnore]
public string MyValue{get;set;}

public string MyValueForJson {get{return MyValue;}

but it is a last resort. Is there some way - other than custom converters etc. - to express that I don't want that field to be populated during deserialization?


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/31722033/json-net-webapi2-serialize-property-but-skip-during-deserialization

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