How to deserialize an API response with the same name but different type

Viewed 239

I'm having trouble with de-serializing an API response. The response returns an object. One of the property's in that object can either be a boolean or an object. When de-serializing it in C# I get an de-serialization error. How do i differentiate between the two data types?

Deserializer:

JsonSerializer.Deserialize<IEnumerable<ApiResponse>>(response)

ApiResponse Object:

public class ApiResponse
{
  [JsonPropertyName("site")]
  public bool SiteBool { get; set; }
    
  [JsonPropertyName("site")]
  public SiteObject Site { get; set; }
}
    
public class SiteObject
{
  [JsonPropertyName("id")]
  public string Id { get; set; }

  [JsonPropertyName("url")]
  public string Url { get; set; }
}
1 Answers

You need to use a JsonConverter for this purpose, classes would be sth like this:

public class ApiResponse
{
  [JsonPropertyName("site")]
  [JsonConverter(typeof(SiteJsonConverter))]
  public ISite Site { get; set; }
   
}
    

public class IsSite : ISite
{
  public bool Value { get; set; }
}

public class SiteObject : ISite
{
  public string Id { get; set; }

  public string Url { get; set; }
}

And converter like this, but to implement the converter properly I suggest you to read https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-converters-how-to

public class SiteJsonConverter : JsonConverter<ISite>
{
    public override ISite Read(ref Utf8JsonReader reader,
            Type typeToConvert,
            JsonSerializerOptions options)
    {
       //Add conversion code here 
    }

    public override void Write(Utf8JsonWriter writer,
            DateTimeOffset dateTimeValue,
            JsonSerializerOptions options)
    {
        throw new NotImplementedException();
    }
}

This code is just an example to show the idea, you need to adjust it to your need

Related