Search code examples
c#jsonjson.netdeserializationjson-deserialization

How to conditionally deserialize a json based on the property value


I have a json incoming and I want to deserialize to the Class only if a property value is matching a specific string. eg: My json is :

[
{
"string1": "a";
"string2": "b";
"string3": "c";
isActive: true
},
{
"string1": "d";
"string2": "e";
"string3": "f";
isActive: false
}
]

My Class is:

public class InboundJson
{
    public string string1 { get; set; }
    public string string2 { get; set; }
    public string string3 { get; set; }
    public bool isActive { get; set; }
}

InboundJson jsonobj = JsonConvert.DeserializeObject<InboundJson>(result);

This works fine and converts the incoming json to object of InboundJson class.

As you can see I have a json array with two parts. I need to deserialize in to the class only if isActive == false.

Any idea how this is possible?(other than manipulating the incoming json string)


Solution

  • Any idea how this is possible?

    This is not possible.

    As @PalleDue said, you can do it post deserialization using .Where() clause

    List<InboundJson> jsonobj = JsonConvert.DeserializeObject<List<InboundJson>>(result);
    
    var result = jsonobj.Where(x => x.isActive);