简体   繁体   English

反序列化 JSON 对象与数组

[英]Deserialization JSON object vs. array

I get the following JSON-Message as a return from a REST-API:我从 REST-API 得到以下 JSON 消息作为返回:

{
   "result":{
      "CONTACT":[
         102565, 
         523652
      ],
      "COMPANY":[
         30302
      ]
   }
}

for deserializing I use Newtonsoft.Json with the following classes:对于反序列化,我将 Newtonsoft.Json 与以下类一起使用:

public class DuplicateResponseBody {
    [JsonProperty("result")]
    public ContactCompany Result { get; set; }
}

public class ContactCompany {
    [JsonProperty("CONTACT")]
    public int[] ContactIds { get; set; }
    [JsonProperty("COMPANY")]
    public int[] CompanyIds { get; set; }
}

this is working without problems.这工作没有问题。

But when there are no values, the REST-Response looks like但是当没有值时,REST-Response 看起来像

{
   "result":[]
}

the result is not an array and the deserialization would not working anymore.结果不是数组,反序列化将不再起作用。 I cannot change the REST-API.我无法更改 REST-API。

Does someone have an Idea, how can I solve the problem on the deserialization-step?有人有想法,我该如何解决反序列化步骤的问题?

I don't think that you need any converters, it would be enough just to add a json constructor to your class我认为您不需要任何转换器,只需将 json 构造函数添加到您的类就足够了

public class DuplicateResponseBody
{
    [JsonProperty("result")]
    public ContactCompany Result { get; set; }
    
    [Newtonsoft.Json.JsonConstructor]
    public  DuplicateResponseBody(JToken result)
    {
         if ( result.Type.ToString()!="Array")
         Result= result.ToObject<ContactCompany>();
    }

    public DuplicateResponseBody() {}
}

You could implement custom JsonConverter for that property and treat an array as null .您可以为该属性实现自定义JsonConverter并将数组视为null

public class ContactCompanyConverter : JsonConverter<ContactCompany>
{
    public override ContactCompany ReadJson(
        JsonReader reader,
        Type objectType,
        ContactCompany existingValue,
        bool hasExistingValue,
        JsonSerializer serializer)
    {
        var token = JToken.Load(reader);
        return token.Type != JTokenType.Array ? token.ToObject<ContactCompany>() : null;
    }

    public override void WriteJson(
        JsonWriter writer,
        ContactCompany value,
        JsonSerializer serializer)
    {
        var token = JToken.FromObject(value);
        token.WriteTo(writer);
    }
}

In order to use the converter, just pass it through the JsonConverterAttribute on your property.为了使用转换器,只需通过您的属性上的JsonConverterAttribute传递它。

public class DuplicateResponseBody
{
    [JsonProperty("result")]
    [JsonConverter(typeof(ContactCompanyConverter))]
    public ContactCompany Result { get; set; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM