【问题标题】:How to parse JSON object into KeyValuePair Array如何将 JSON 对象解析为 KeyValuePair 数组
【发布时间】:2013-11-25 20:44:07
【问题描述】:

我正在尝试解析:

{"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数组中,但只能在解析成字典时才能序列化。

这不起作用:

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

但这会,但是我想要一个键值对数组而不是数组列表字典:

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。

【问题讨论】:

    标签: arrays json vb.net serialization javascriptserializer


    【解决方案1】:

    您提供的 JSON 不能直接序列化为 KeyValuePairs 的列表/数组(错误本身就说明了问题)。

    但是,您可以使用“临时”类型并将提供的 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()
    

    【讨论】:

    • 是的,这行得通,只是跳跃我可以直接解析成一个 KeyValuePair 数组。无论如何,我决定只使用字典:keyVals = serializer.Deserialize(Of Dictionary(Of String, Object))(Keys) For Each item In keyVals("keys") If item("key") = "Path" Then request = XElement.Load(item("value")) End If Next
    • 另外,我的 WCF 使用完全相同格式的 json 对象,并且操作协定中的参数是键值对数组,所以我认为可能有一种简单的方法来模拟它。
    • 无法直接解析成KeyValuePair,因为它没有无参构造函数。您确实也可以执行上述操作:)。
    猜你喜欢
    • 2019-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 2020-05-02
    • 2020-09-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多