反序列化格式错误的Json返回空数组

时间:2016-07-20 14:22:02

标签: arrays json vb.net deserialization malformed

请使用VB.NET Http Requests从Web服务中读取数据。它曾用这种方式发送数据:

[
    {
      "id": 7532,
      "nome": "LABOR INC.",
      "isClient": false,
      "personality": {
        "id": 2,
        "value": "CORPORATION"
      },
      "registryNumbers": [
        {
          "id": 9378,
          "number": "20786790174"
        }
      ],
      "personality_id": 2
    },
    {
      "id": 7537,
      "nome": "JOSE SILVA",
      "isClient": false,
      "personality": {
        "id": 1,
        "value": "PERSON"
      },
      "gender": {
        "id": 1,
        "value": "MALE"
      },
      "cityOfBirth": {
        "id": 355030,
        "value": "SAO PAULO"
      },
      "nationality": {
        "id": 85,
        "value": "BRAZILIAN"
      },
      "registryNumbers": [
        {
          "id": 9383,
          "number": "03217495388"
        }
      ],
      "personality_id": 1
    }
]

没关系,因为省略了未使用的字段(如公司的“性别”和“cityOfBirth”)。但是,有些日子以来,它开始将这些字段作为空数组([])发送回来,如下所示:

{
  "id": 7532,
  "nome": "LABOR INC.",
  "isClient": false,
  "personality": {
    "id": 2,
    "value": "CORPORATION"
  },
  "gender": [],
  "cityOfBirth": [],
  "nationality": [],
  "registryNumbers": [
    {
      "id": 9378,
      "number": "20786790174"
    }
  ],
  "personality_id": 2
}

因为它使反序列化类中的命运属性不匹配,因为它们不是(也不可能是)枚举/数组而是单个对象。

我的问题:是否有一些反序列化扩展或属性我可以添加到我的类中,以便将那些([])反序列化为null / Nothing?特别要感谢VB.NET,但我也能够阅读和修改C#。

也就是说,我想知道当一个数组被“强制”进一个需要单个对象的属性时,我怎么能让代码停止,并在此时做适当的处理。

1 个答案:

答案 0 :(得分:0)

尝试使用自定义转换器解决问题:

Public Class BogusArrayJsonConverter
    Inherits JsonConverter
    Public Overrides Function CanConvert(objectType As Type) As Boolean
        Return GetType(MyRecord).IsAssignableFrom(objectType)
    End Function
    Public Overrides Function ReadJson(reader As JsonReader, objectType As Type, existingValue As Object, serializer As JsonSerializer) As Object
        If reader.TokenType = JsonToken.StartArray Then
            Return serializer.Deserialize(Of MyRecord())(reader).SingleOrDefault
        Else
            Return serializer.Deserialize(Of MyRecord)(reader)
        End If
    End Function
    Public Overrides Sub WriteJson(writer As JsonWriter, value As Object, serializer As JsonSerializer)
        Throw New NotImplementedException()
    End Sub
End Class

感谢所有试图帮助我的人。