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

Deserialize malformed Json returning empty arrays

拜托,我使用 VB.NET Http 请求从网络服务读取数据。它曾经以这种方式发送数据:

[
    {
      "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
    }
]

没关系,因为省略了未使用的字段(如 "gender" 和 "cityOfBirth" 用于公司)。然而,有些日子以来,它开始将这些字段作为空数组 ([]) 发回,如下所示:

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

因此,它与反序列化中的命运属性不匹配 class,因为这些不是(也不可能)enumerations/arrays,而是单个对象。

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

也就是说,我想知道当数组 "forced" 变成需要单个对象的 属性 时如何让我的代码停止,并在此时进行适当的处​​理.

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

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

感谢所有帮助过我的人。