Search code examples
c#asp.net-corejson.netjson-deserialization

How to ignore a property from serialization but keep in for deserialization using json.net in c#


How to ignore a property from serialization but keep in for deserialization using json.net in c#.

Example:

public class Foo
{
    [JsonProperty("id")]
    public int Id { get; set; }

    [JsonProperty("contentType")]
    public object ContentType { get; set; }

    [JsonProperty("content")]
    public object Content { get; set; }

    [JsonIgnore]
    public Relationship RelationshipContent { get; set; }

    [JsonIgnore]
    public Domains DomainContent { get; set; }

}

in the above code i need to deserialize the "content" into the property "RelationshipContent" and "DomainContent" according to the value to the PartType property value.

Can you help me how to do it in C# using Newtonsoft.Json?


Solution

  • Could you have a method for the 'set' of Content and process the data into the right place.

    public class Foo
    {
        [JsonProperty("id")]
        public int Id { get; set; }
    
        [JsonProperty("contentType")]
        public object ContentType { get; set; }
    
        [JsonProperty("content")]
        public object Content { get; set {
                //do something here with `value` e.g.
                RelationshipContent = value; //change as required
                DomainContent = value; //change as required
            }
        }
    
        [JsonIgnore]
        public Relationship RelationshipContent { get; set; }
    
        [JsonIgnore]
        public Domains DomainContent { get; set; }
    
    }