Search code examples
arraysjsonvb.netserializationjavascriptserializer

How to parse JSON object into KeyValuePair Array


I am trying to parse:

{"keys":[{"key":"IDVal7","value":"12345"},{"key":"IDVal6","value":"12345"},{"key":"IDVal5","value":"12345"},{"key":"IDVal4","value":"12345"},{"key":"IDVal3","value":"12345"},{"key":"IDVal2","value":"12345"},{"key":"IDVal1","value":"12345"},{"key":"FilePathAndName","value":"c:\\my.xml"}]}

into an array of KeyValuePairs, but can only get it to serialize when parsing into a Dictionary.

this does not work:

Dim keyVals As New Dictionary(Of String, KeyValuePair(Of String, String))
        Dim serializer As New System.Web.Script.Serialization.JavaScriptSerializer
        Try
            keyVals = serializer.Deserialize(Of Dictionary(Of String, KeyValuePair(Of String, String)))(Keys)           

        Catch ex As Exception

        End Try

but this will, however I want an array of keyvaluepairs and not a dictionary of arraylists:

Dim keyVals As New Dictionary(Of String, Object)
        Dim serializer As New System.Web.Script.Serialization.JavaScriptSerializer
        Try
            keyVals = serializer.Deserialize(Of Dictionary(Of String, Object))(Keys)
        Catch ex As Exception

        End Try

Anyone have Ideas on how to do this? Also, I cannot use JSON.net.


Solution

  • Your provided JSON can't be directly serialized as a list / array of KeyValuePairs (the errors kinda speaks for themselves).

    You could however use a "temporary" type and deserialize the provided JSON into that object and then convert it to a KeyValuePair.

    For example, your "temporary" object could be something like this:

    Class KeysDTO
        Class KeyValue
            Public Property Key As String
            Public Property Value As String
        End Class
    
        Public Property Keys As List(Of KeyValue)
    End Class
    

    And your deserializing would be:

    Dim serializer As New System.Web.Script.Serialization.JavaScriptSerializer()
    Dim dto As KeysDTO = serializer.Deserialize(Of KeysDTO)(keys)
    
    ' If you really want an array of KeyValuePairs, you can do this then
    Dim keyValuePairs = dto.Keys.Select(Function(kv) New KeyValuePair(Of String, String)(kv.Key, kv.Value)).ToArray()