Search code examples
c#jsonjson-deserialization

Unusual JSON construct


I am supposed to read the following JSON response:

ValueFilters:[
{field:"amount", comparitor:"GREATER", "value": 0},
{operator:"AND"},
{field:"id", comparitor:"LESS", "value": 5}]

If it did not contain 'operator' object then I would not have any problem, but with it how do I construct the equivalent C# object?


Solution

  • First off, your example, the JSON is not valid JSON. To make it valid, one must add quotes to each of the property names such as field to "field". Once that is done the Json can be parsed:

    {
      "ValueFilters": [
        {
          "field": "amount",
          "comparitor": "GREATER",
          "value": 0
        },
        {
          "operator": "AND"
        },
        {
          "field": "id",
          "comparitor": "LESS",
          "value": 5
        }
      ]
    }
    

    By taking that valid Json above it can be serialized into these C# classes:

    public class Filters
    {
        public List<ValueFilter> ValueFilters { get; set; }   
    }
    
    public class ValueFilter
    {
        [JsonPropertyName("operator")]        // Handle the C# `operator` keyword.
        public string Operator { get; set; }
        
        public string field { get; set; }
    
        public string comparitor { get; set; } // Misspell -> comparator
    
        public int value { get; set; }
    
    } 
    

    Using your favorite derializer would look like this, .Net 5 System.Text.Json shown:

    var filter = JsonSerializer.Deserialize<Filters>(data);
    

    Which when deserialized you have 3 ValueFilter items. By checking whether the Operator property is not null or not, the future code knows what to do with the data.

    Operator field comparitor value
    null amount GREATER 0
    AND null null 0
    null id LESS 5