How to parse JSON Response into Dictionary?

半城伤御伤魂 提交于 2019-12-24 06:35:17

问题


I have a JSON resonse (HTTPWebResponse) coming back from my WCF Service. It looks like this :

{
    "New SessionResult": [
        {
            "Key": "Token",
            "Value": "token_value"
        }
    ]
}

I am using JSON.NET (http://james.newtonking.com) and I cant figure out how to deserialize this response into a Dictionary<string, string>. I have tried several things but each one says in different wording "cannot convert JSON into sting". Currently I tried this :

Dictionary<string, string> values = JsonConvert.DeserializeObject<Dictionary<string, string>>(reader.ReadToEnd());

If possible I could just get certain values to place directly into strings. Example) JSON response has key,value pair (Token,token_value), I want to get the value for the key "Token" and place it in the local string "string Token".

Anyone help please, thanks.


回答1:


You should try the Newtonsoft.Json plugin: http://json.codeplex.com/

in your case you'd end up with something like:

 JObject json = JObject.Parse(jsonResponseData);
 ...
 mydic.Add(json["New SessionResult"]["Key"], json["New SessionResult"]["Value"]



回答2:


Why change your code?

Just convert from "string, string" -> "string, dynamic" in your declaration.

Dictionary<string, string> values = JsonConvert.DeserializeObject<Dictionary<string, string>>(reader.ReadToEnd());


来源:https://stackoverflow.com/questions/6375122/how-to-parse-json-response-into-dictionary

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!