Home > Software engineering >  Deseralize JSON where property can be of different types
Deseralize JSON where property can be of different types

Time:11-06

When calling an external API that returns a list and deserializing, one of the list item properties can be of type string or an object. I want to deserialize all objects to object and for strings just set the property as null. Can you do it somehow to specify the behavior of fallback in order to prevent System.Text.Json.JsonException: 'The JSON value could not be converted to ... exception?

public class ListItem 
{
    [JsonPropertyName["location"]
    public Location Location { get;set; }
}

// ...

public class Location
{
    [JsonPropertyName("city")]
    public string City { get; set; }

    [JsonPropertyName("country")]
    public string Country { get; set; }
}

And the API responds with:

[
  {
     "location": "some location",
     // ...
  },
  {
     "location":
        {
            "city": "some city",
            "city": "some country"
        }
  }
]

CodePudding user response:

I am using Newtonsoft.Json and constructor

using Newtonsoft.Json;

List<ListItem> locations = JsonConvert.DeserializeObject<List<ListItem>>(json);

public class ListItem
{
    [JsonIgnore]
    public Location Location { get; set; }

    [JsonConstructor]
    public ListItem(JToken location)
    {
        if (location.Type == JTokenType.String)
            Location = new Location { City = (string)location };
        else Location = location.ToObject<Location>();
    }
}
  • Related