3

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.

Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108
VaasLolla
  • 51
  • 1
  • 1
  • 5

1 Answers1

3

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);
lucky
  • 12,734
  • 4
  • 24
  • 46
  • i am getting the error below when i tried to add this in : Type 'SampleJson' is not supported for deserialization of an array. at System.Web.Script.Serialization.ObjectConverter.ConvertListToObject(IList list, Type type, JavaScriptSerializer serializer, Boolean throwOnError, IList& convertedList) at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeInternal(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object& convertedObject) at – VaasLolla Dec 13 '17 at 12:59
  • Are you sure that json string which you are trying to deserialize is same with json which you shared in question ? – lucky Dec 13 '17 at 13:03
  • As the earlier error was invalid Array showing the "[" as the reason, i have tried by removing the same. except that the json is "[" which are in between and left all of them in the same string – VaasLolla Dec 13 '17 at 13:11
  • here is the string i used .. {"vars":[ {"name":"abcd","value":"true"}, {"name":"efgh","value":"false"}, {"name":"xyz","value":"sring1"}, {"name":"ghi","value":"string2"}, {"name":"jkl","value":"num1"} ,"OtherNames":"String12345"}] – VaasLolla Dec 13 '17 at 13:13
  • The json which you are trying to deserialize is wrong. Check it here; https://jsonformatter.curiousconcept.com/ – lucky Dec 13 '17 at 13:50
  • That worked right away with the JSON String corrected. – VaasLolla Dec 13 '17 at 14:25