Deserialize JSON with varying element names

后端 未结 1 1391
长发绾君心
长发绾君心 2020-12-21 17:50

I\'m struggling deserializing an json into an vb.net object with newtonsoft. The problem is, that the element name of the following array is different for each array:

<
相关标签:
1条回答
  • 2020-12-21 18:08

    You can almost always map the data to a Dictionary(Of String, T) where the key/string will be the property name and the T is a class to hold the data. With a simple property, that could be string, int, date etc. It would be ideal for this sort of thing, but T would be a class. The classes:

    Public Class ItemData
        Public Property key As String
        Public Property md5sum As String
        Public Property entity_metadata As EntityMetadata
    End Class
    
    Public Class EntityMetadata
        Public Property document_index_end As String()
        Public Property document_index_start As String()
    End Class
    

    If you use a robot to make these (such as in Visual Studio: Edit menu, Paste Special, Paste JSON as classes), there is a bit of cleanup to do. The robots are not terribly clever so they make Entity_Metadata1, Entity_Metadata2 etc. Since the make up is identical, you can distill it to just one.

    Another thing is arrays. They will create:

    Public Class Entity_Metadata###
        Public Property document_index_end() As String
        Public Property document_index_start() As String
    End Class
    

    But the correct syntax ought to be ...As String() Then deserialize:

    Dim items = JsonConvert.DeserializeObject(Of Dictionary(Of String, ItemData()))(jstr)
    
    ' test/proof:
    ' the As... is important so that the Value gets cast correctly
    For Each kvp As KeyValuePair(Of String, ItemData()) In items
    
        Console.WriteLine("key: {0}, MD5: {1}, ndx end {2}",
                          kvp.Key,
                          kvp.Value(0).md5sum,
                          kvp.Value(0).entity_metadata.document_index_end(0))
    Next
    

    Results:

    key: ABC, MD5: e24cb0e730269e419f036a10dd6c38d0, ndx end 3162
    key: UZT, MD5: dfed620a43ed7dcc2f0923337b9a75b0, ndx end 92
    key: NEQUZ, MD5: 8b7bf4c2477ec72e0577aa5c968ffa1c, ndx end 3686
    key: NUTRF, MD5: a730b1bf89fd4da9986edeb931f3e507, ndx end 1133

    In practice, since ItemData is an array as are the index props, you may want or need to test the length.

    0 讨论(0)
提交回复
热议问题