【问题标题】:How to deserialize an API response with the same name but different type如何反序列化具有相同名称但不同类型的 API 响应
【发布时间】:2021-01-19 05:28:11
【问题描述】:

我在反序列化 API 响应时遇到问题。响应返回一个对象。该对象中的属性之一可以是布尔值或对象。在 C# 中对其进行反序列化时,出现反序列化错误。如何区分这两种数据类型?

反序列化器:

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

ApiResponse 对象:

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; }
}

【问题讨论】:

  • 使用objectdynamic。 C# 没有联合类型,因此您只需选择一个上限类型
  • 你得到什么错误?
  • @AluanHaddad 使用动态似乎可以否定反序列化错误!
  • @devNull InvalidOperationException:“ApiResonse.SiteObject”的 JSON 属性名称与另一个属性冲突。
  • 您只需创建一个属性并删除另一个属性

标签: c# asp.net json api


【解决方案1】:

为此,您需要使用JsonConverter,类会是这样的:

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; }
}

和这样的转换器,但要正确实现转换器我建议你阅读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();
    }
}

此代码只是一个展示想法的示例,您需要根据需要对其进行调整

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多