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

前端 未结 4 1098
迷失自我
迷失自我 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:17

    Thanks to both crowcoder & Kundan. I combined the two approaches and came up with something that works with both json inputs. Here is the final code.

    Public Class jsonCar
        Public Property make As String
        Public Property model As String
        Public Property linesArray As List(Of jsonCarLines)
        Public Property year As String
    End Class
    
    Public Class jsonCarLines
        Public Property line As String
        Public Property engine As String
        Public Property color As String
    End Class
    
    Module Module1
        'Private Const json As String = "{""Make"":""Dodge"",""Model"":""Charger"",""Lines"": [{""line"":""base"",""engine"": ""v6"",""color"":""red""},{""line"":""R/T"",""engine"":""v8"",""color"":""black""}],""Year"":""2013""}"
        Private Const json As String = "{""Make"":""Dodge"",""Model"":""Charger"",""Lines"": {""line"":""R/T"",""engine"":""v8"",""color"":""black""},""Year"":""2013""}"
        Sub Main()
    
            Dim obj As JObject = JsonConvert.DeserializeObject(json)
            Dim ln As JToken = obj("Lines")
    
            Dim car As jsonCar = JsonConvert.DeserializeObject(Of jsonCar)(json)
    
            If (ln.GetType() Is GetType(Newtonsoft.Json.Linq.JArray)) Then
                car.linesArray = JsonConvert.DeserializeObject(Of List(Of jsonCarLines))(JsonConvert.SerializeObject(ln))
            End If
    
            If (ln.GetType() Is GetType(Newtonsoft.Json.Linq.JObject)) Then
                car.linesArray = New List(Of jsonCarLines)
                car.linesArray.Add(JsonConvert.DeserializeObject(Of jsonCarLines)(JsonConvert.SerializeObject(ln)))
            End If
    
            Console.WriteLine("Make: " & car.make)
            Console.WriteLine("Model: " & car.model)
            Console.WriteLine("Year: " & car.year)
            Console.WriteLine("Lines: ")
            For Each line As jsonCarLines In car.linesArray
                Console.WriteLine("    Name: " & line.line)
                Console.WriteLine("    Engine: " & line.engine)
                Console.WriteLine("    Color: " & line.color)
                Console.WriteLine()
            Next
            Console.ReadLine()
        End Sub
    
    End Module
    

    Big thanks for the quick replies. This solved something I'd been spending a lot time off-and-on trying to figure out.

提交回复
热议问题