1

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

Tanveer Badar
  • 5,438
  • 2
  • 27
  • 32
  • Could you use two classes, one inherited from the other, then serialize to the parent class and deserialize to the child class? – AGB Aug 02 '17 at 11:47
  • I've done something reasonably similar recently and used the custom JsonConverter option. What i did was add a Custom Attribute to the Properties and in the custom JsonConverter used Reflection to get all the properties and change the serialisation logic depending on the attribute. Think something along those lines should work for you. – ajg Aug 02 '17 at 12:03

1 Answers1

0

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; 
    } 
}
jason.kaisersmith
  • 8,712
  • 3
  • 29
  • 51