How to deserialize JSON which can be an array or a single object

前端 未结 4 1028
迷失自我
迷失自我 2021-01-13 04:45

I\'m fairly new to using JSON.net and having trouble with some json I\'m getting which sometime comes in as an array and sometimes as single object. Here is an example of wh

4条回答
  •  生来不讨喜
    2021-01-13 05:32

    Here is how to get the SingleOrArrayConverter solution in the linked duplicate question working for your use case.

    First, here is the VB-translated converter code. Take this and save it to a class file somewhere in your project. You can then easily reuse it for any future cases like this.

    Imports Newtonsoft.Json
    Imports Newtonsoft.Json.Linq
    
    Public Class SingleOrArrayConverter(Of T)
        Inherits JsonConverter
    
        Public Overrides Function CanConvert(objectType As Type) As Boolean
            Return objectType = GetType(List(Of T))
        End Function
    
        Public Overrides Function ReadJson(reader As JsonReader, objectType As Type, existingValue As Object, serializer As JsonSerializer) As Object
            Dim token As JToken = JToken.Load(reader)
    
            If (token.Type = JTokenType.Array) Then
                Return token.ToObject(Of List(Of T))()
            End If
    
            Return New List(Of T) From {token.ToObject(Of T)()}
        End Function
    
        Public Overrides ReadOnly Property CanWrite As Boolean
            Get
                Return False
            End Get
        End Property
    
        Public Overrides Sub WriteJson(writer As JsonWriter, value As Object, serializer As JsonSerializer)
            Throw New NotImplementedException
        End Sub
    
    End Class
    

    Now that you have this converter, any time you have a property that can be either a list or a single item, all you have to do is declare it as a list in your class and then annotate that list with a JsonConverter attribute such that it uses the SingleOrArrayConverter class. In your case, that would look like this:

    Public Class jsonCar
        Public Property make As String
        Public Property model As String
        
        Public Property lines As List(Of jsonCarLines)
        Public Property year As String
    End Class
    

    Then, just deserialize as you normally would, and it works as expected.

    Dim car As jsonCar = JsonConvert.DeserializeObject(Of jsonCar)(json)
    

    Here is a complete demonstration: https://dotnetfiddle.net/msYNeQ

提交回复
热议问题