我正在尝试解析:
{"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"}]}
进入KeyValuePairs数组,但只能在解析为Dictionary时将其序列化。
这不起作用:
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
但是这会,但是我需要一组keyvaluepairs而不是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
任何人都有关于如何做到这一点的想法?另外,我不能使用JSON.net。
答案 0 :(得分:1)
您提供的JSON无法直接序列化为KeyValuePair
的列表/数组(错误有点说明了自己)。
但是,您可以使用“临时”类型并将提供的JSON反序列化为该对象,然后将其转换为KeyValuePair。
例如,您的“临时”对象可能是这样的:
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
你的反序列化将是:
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()