使用VB.Net反序列化JSON对象

时间:2014-04-06 21:09:29

标签: c# .net json vb.net

我有一个VB.Net Windows应用程序,它对一个C#Web应用程序进行RESTful WS调用,该应用程序使用JSON.Net来序列化包含在 Dictionary<String, String>

来自C#Web应用程序的响应以JSON字符串形式返回,如下所示:

"{"8bf370f3-d258-40d3-a659-063db90f5291":"String1","5a0248de-7139-44ba-991b-072d598ff9ab":"String2"}"

在VB.Net端,我使用JSON.Net尝试反序列化响应,我收到此错误:

Error converting value 
"{"8bf370f3-d258-40d3-a659-063db90f5291":"String1","5a0248de-7139-44ba-991b-072d598ff9ab":"String2"}"
to type 'System.Collections.Generic.Dictionary`
2[System.String,System.String]'. Path '', line 1, position 1383.

这是VB.Net代码:

..
..
reader = New StreamReader(response.GetResponseStream())

' Console application output 

Dim responseStr As String = reader.ReadToEnd
'MsgBox(responseStr)

'Error occurs on the next line.
Dim dict As Dictionary(Of String, String) = JsonConvert.DeserializeObject(Of Dictionary(Of String, String))(responseStr)

Dim pair As KeyValuePair(Of String, String)
For Each pair In dict
    MsgBox("Key: " & pair.Key.ToString & " Value: " & pair.Value)
Next
..
..

我尝试使用“Object”作为类型而不是String,我得到了同样的错误。我看不出JSON本身有什么问题或者反序列化方法调用有什么问题所以我很茫然。任何建议都将不胜感激。

1 个答案:

答案 0 :(得分:0)

我认为你JSON需要看起来像这样:

[{"8bf370f3-d258-40d3-a659-063db90f5291":"String1"},{"5a0248de-7139-44ba-991b-072d598ff9ab":"String2"}]

Dictionary是键/值对的集合,您的JSON中没有项目集合,只有一个具有4个属性的对象。