How to define variable in class to receive either List<string> or string when deserializing JSON?

Viewed 125

Is there a way to declare a class where for a specific variable I can receive either a List or a string?

I trying to deserialize a JSON and it can come in one of the formats below:

"MercadoriasPresencaCarga": {
  "Mercadoria": 7693066,
  "Descarga": "08/07/2017 13:35:39"
},

or

 "MercadoriasPresencaCarga": {
  "Mercadoria": [
    "7693066"
  ],
  "Descarga": [
    "08/07/2017 13:35:39"
  ]
},

The class for this block is created like this:

public class MercadoriasPresencaCarga
{
    public List<string> Mercadoria { get; set; }

    public List<string> Descarga { get; set; }
}

The problem is that if this block of JSON come as the first format that I showed where it is not a array, it will cause an error on it deserialization.

How could I solve this problem?

1 Answers

Ideally the json should always come in the same format, but if that's not a possibility there are some workarounds.

Both json strings will deserialize successfully using the following class:

public class Model
{
    // other properties here 
    // ....

    [JsonIgnore]
    public string Mercadoria => GetValue("Mercadoria");

    [JsonIgnore]
    public string Descarga => GetValue("Descarga");

    public JObject MercadoriasPresencaCarga { get; set; }


    private string GetValue(string path)
    {
        if (MercadoriasPresencaCarga == null)
        {
            return null;
        }

        string value = null;
        JToken token = MercadoriasPresencaCarga.SelectToken(path);

        if (token.Type == JTokenType.Array && token.HasValues)
        {
            value = token.First.Value<string>();
        }
        else
        {
            value = token.Value<string>();
        }

        return value;
    }
}

Please note that:

  • MercadoriasPresencaCarga will be deserialized as JObject
  • Both Mercadoria and Descarga are non-serializable properties (marked with [JsonIgnore])

Testing the code - json string with string properties (no arrays):

string json1 = @"{
    ""MercadoriasPresencaCarga"": {
      ""Mercadoria"": 7693066,
      ""Descarga"": ""08/07/2017 13:35:39""
    }
}";

Model model1 = JsonConvert.DeserializeObject<Model>(json1);

Console.WriteLine($"Descarga: {model1.Descarga}, Mercadoria: {model1.Mercadoria}");

Testing the code - json string with arrays:

string json2 = @"{
    ""MercadoriasPresencaCarga"": {
      ""Mercadoria"": [
        ""7693066""
      ],
      ""Descarga"": [
        ""08/07/2017 13:35:39""
      ]
    }
}";

Model model2 = JsonConvert.DeserializeObject<Model>(json2);

Console.WriteLine($"Descarga: {model2.Descarga}, Mercadoria: {model2.Mercadoria}");
Related