JsonConvert .NET Serialize/Deserialize Read Only [duplicate]

百般思念 提交于 2019-12-11 08:26:56

问题


I'm working with a REST Api at the moment which I have no control over and have built models to correspond with the json which I receive from the Api.

The Api in question though doesn't allow me to push the whole model back when doing a post so I need to find a way to Deserialize the json in full but only write selected data when Serializing.

So far I have tried JsonIgnore which does what it says on the tin and completely ignores the property.

I then created a Custom Attribute JsonWriteAttribute and applied it to the properties I want to serialise.

I've looked at overriding the DefaultContractResolver CreateProperties method to then only get properties with the attribute but I cant seem to determine from the method or a property in the Resolver if I'm doing a read or write.

I've also tried looking at a custom JsonConverter but it seems like from that I cant interrupt a pipeline and have to then handle all the write myself. Am I missing something here as it seems like the right idea?

Anyone figured out a way to mark a property as ReadOnly when doing serialisation, deserialization using Json.Net?

Thanks


回答1:


One possibility to conditional serialise a property is the ShouldSerialize

http://www.newtonsoft.com/json/help/html/ConditionalProperties.htm

You create a method which returns a bool to determine if your property should be serialized or not. The Method starts with ShouldSerialize and ends with your property name. e.g. ShouldSerializeMyProperty

An example

public MyClass
{   
    public string MyProp { get; set; }
    public string ExcludeThisProp { get; set; }
    public int MyNumber { get; set; }
    public int ExcludeIfMeetsCondition { get; set; }

    //Define should serialize options       
    public bool ShouldSerializeExcludeMyProp() { return (false); } //Will always exclude
    public bool ShouldSerializeExcludeIfMeetsCondition() 
    { 
        if (ExcludeIfMeetsCondition > 10)
            return true;
        else if (DateTime.Now.DayOfWeek == DayOfWeek.Monday)
            return true;
        else
            return false; 
    } 
}


来源:https://stackoverflow.com/questions/45459995/jsonconvert-net-serialize-deserialize-read-only

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