Search code examples
c#jsonjavascriptserializer

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.


Solution

  • 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);