简体   繁体   中英

Deserialize JSON Object using VB.Net

I have a VB.Net windows application that makes a RESTful WS call to a C# web application that uses JSON.Net to serialize the results that are contained in a Dictionary<String, String> .

The response from the C# web application comes back as a JSON string that looks like this:

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

On the VB.Net Side, I use JSON.Net to try to Deserialize the response and I get this error:

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.

Here is the VB.Net code:

..
..
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
..
..

I have tried using "Object" as the type instead of String, and I get the same error. I can't see anything wrong with the JSON itself or anything wrong with the deserialization method call so i'm at a loss. Any advice would be greatly appreciated.

I think that you JSON needs to look like this:

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

Dictionary is a collection of key/value pairs and you have no collection of items in your JSON only a single object with 4 properties.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM