Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize KeyValuePair<string, string> Json.Net

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?

like image 425
TorbenJ Avatar asked Nov 08 '12 20:11

TorbenJ


1 Answers

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>>();
like image 149
L.B Avatar answered Sep 30 '22 18:09

L.B