简体   繁体   中英

How to parse a JSON string in to a name value pair in C#

I have to parse the JSON string in to a name value pair list :

{"vars":[
 {"name":"abcd","value":"true"},
 {"name":"efgh","value":"false"},
 {"name":"xyz","value":"sring1"},
 {"name":"ghi","value":"string2"},
 {"name":"jkl","value":"num1"}
 ],"OtherNames":["String12345"]}    

I can not add the reference of newtonsoft JsonConvert due to multiple parties involved .

With JavaScriptSerializer i am able to get the json converted to name value only when i have one value in the string but not an array

 JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
 Dictionary<string,string> dict = jsSerializer.Deserialize<Dictionary<string, string>>(jsonText);

I think the declaration which says i will get the array values is missing somewhere.

You can't deserialize that Json as Dictionary<string, string> . Because the json contains two different array and you should use complex object to deserialize it like this;

public class Var
{
    public string name { get; set; }
    public string value { get; set; }
}

public class SampleJson
{
    public List<Var> vars { get; set; }
    public List<string> OtherNames { get; set; }
}


JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
var sampleJson = jsSerializer.Deserialize<SampleJson>(jsonText);

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