如何在C#中将JSON字符串解析为名称值对
作者:互联网
我必须将JSON字符串解析为一个名称值对列表:
{"vars":[
{"name":"abcd","value":"true"},
{"name":"efgh","value":"false"},
{"name":"xyz","value":"sring1"},
{"name":"ghi","value":"string2"},
{"name":"jkl","value":"num1"}
],"OtherNames":["String12345"]}
由于涉及多个方面,因此我无法添加newtonsoft JsonConvert的引用.
使用JavaScriptSerializer,仅当我在字符串中有一个值但没有数组时,才能够将json转换为名称值
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
Dictionary<string,string> dict = jsSerializer.Deserialize<Dictionary<string, string>>(jsonText);
我认为声明我将获得数组值的声明在某处丢失.
解决方法:
您不能将该Json反序列化为Dictionary< string,string>.因为json包含两个不同的数组,所以您应该使用复杂的对象对它进行反序列化;
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);
标签:javascriptserializer,json,c 来源: https://codeday.me/bug/20191110/2014315.html