6

I need to deserialize a string like this

{
  "example": {
    "id": "12345",
    "name": "blabla"
  }
}

into a KeyValuePair<string, string> or something similiar.

I tried:

var pair = JsonConvert.DeserializeObject<KeyValuePair<string, string>>(d["example"].ToString()); 

(d["example"] returns the json string like shown above)

The result was an empty KeyValuePair<string, string>.

Is there any way to solve this?

4

1 回答 1

7
string json = 
     @"{
          ""example"": {
          ""id"": ""12345"",
          ""name"": ""blabla""
          }
        }";

var jobj =  JObject.Parse(json);
var dict = jobj["example"]
            .Children().Cast<JProperty>()
            .ToDictionary(x => x.Name, x => (string)x.Value);

or

var dict = jobj["example"].ToObject<Dictionary<string, string>>();
于 2012-11-08T20:07:42.820 回答