3

我正在使用的 JSON API 之一返回响应,该响应会根据查询返回的结果数量来改变其数据结构。我从 C# 中使用它并使用 JSON.NET 反序列化响应。

这是从 API 返回的 JSON

多结果响应:

{
  "response": {
    "result": {
      "Leads": {
        "row": [
          {
            "no": "1",
...
...
...

单一结果响应:

{
  "response": {
    "result": {
      "Leads": {
        "row": {
          "no": "1",
...
...
...

请注意“行”节点的区别,在多个结果的情况下是数组,在单个结果的情况下是对象。

这是我用来反序列化这些数据的类

课程:

public class ZohoLeadResponseRootJson
{
    public ZohoLeadResponseJson Response { get; set; }
}

public class ZohoLeadResponseJson
{
    public ZohoLeadResultJson Result { get; set; }
}

public class ZohoLeadResultJson
{
    public ZohoDataMultiRowJson Leads { get; set; }
}

public class ZohoDataMultiRowJson
{
    public List<ZohoDataRowJson> Row { get; set; }
}

public class ZohoDataRowJson
{
    public int No { get; set; }
    ...
}

“Multiple Result Response”反序列化没有任何问题,但是当响应中只有一个结果时,由于数据结构的变化,无法反序列化响应。我得到一个例外

Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON 
object (e.g. {"name":"value"}) into type 
'System.Collections.Generic.List`1[MyNamespace.ZohoDataRowJson]' 
because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) 
or change the deserialized type so that it is a normal .NET type (e.g. not a 
primitive type like integer, not a collection type like an array or List<T>) 
that can be deserialized from a JSON object. JsonObjectAttribute can also be 
added to the type to force it to deserialize from a JSON object.

Path 'response.result.Notes.row.no', line 1, position 44.

有没有办法在 Json.Net 中使用一些属性来处理这个问题,并且希望不必编写转换器?

4

1 回答 1

3

灵感来自对类似问题的回答。

public class ZohoDataMultiRowJson
{
    [JsonConverter(typeof(ArrayOrObjectConverter<ZohoDataRowJson>))]
    public List<ZohoDataRowJson> Row { get; set; }
}

public class ArrayOrObjectConverter<T> : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.StartArray)
        {
            return serializer.Deserialize<List<T>>(reader);
        }
        else if (reader.TokenType == JsonToken.StartObject)
        {
            return new List<T>
            {
                (T) serializer.Deserialize<T>(reader)
            };
        }
        else
        {
            throw new NotSupportedException("Unexpected JSON to deserialize");
        }
    }

    public override bool CanConvert(Type objectType)
    {
        throw new NotImplementedException();
    }
}
于 2014-09-08T20:23:45.283 回答