将json格式的string转化为对象
Posted 王炜忠
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将json格式的string转化为对象相关的知识,希望对你有一定的参考价值。
(1)
private void button1_Click(object sender, EventArgs e) { StringBuilder sb = new StringBuilder(); sb.Append("{"); sb.Append("\"search\": null,"); sb.Append("\"totalCount\": 2,"); sb.Append("\"list\": ["); sb.Append("{"); sb.Append("\"id\": \"DE\","); sb.Append("\"name\": \"Herz\""); sb.Append("},"); sb.Append("{"); sb.Append("\"id\": \"E_0\","); sb.Append("\"name\": \"Sciences\""); sb.Append("}"); sb.Append("],"); sb.Append("\"indexId\": null,"); sb.Append("\"success\": true"); sb.Append("}"); //将json对象解析成一个类,注意名称和数据类型必须相符。简便方法:VS的“编辑”-->“选择性粘贴”-->“将JSON粘贴为类”,系统自动生成 #region 方法一:Newtonsoft.Json.JsonConvert.DeserializeObject<> ClassObject co = Newtonsoft.Json.JsonConvert.DeserializeObject<ClassObject>(sb.ToString()); MessageBox.Show(co.list.Length.ToString());//输出2 #endregion #region 方法二:System.Runtime.Serialization.Json.DataContractJsonSerializer //存储流 System.IO.MemoryStream mstream = new System.IO.MemoryStream(Encoding.UTF8.GetBytes(sb.ToString())); //指定反序列化对象 System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(ClassObject)); //进行解析 ClassObject cccoo = (ClassObject)serializer.ReadObject(mstream); MessageBox.Show(cccoo.list.Length.ToString());//输出 #endregion } //电脑生成的:根据json格式的string解析的对象ClassObject和List public class ClassObject { public object search { get; set; } public int totalCount { get; set; } public List[] list { get; set; } public object indexId { get; set; } public bool success { get; set; } } public class List { public string id { get; set; } public string name { get; set; } }
(2)但是,电脑自动生成对象,在解析时并不全是能解析成功的。如下
private void button1_Click(object sender, EventArgs e) { StringBuilder sb = new StringBuilder(); sb.Append("["); sb.Append("{"); sb.Append("\"code\": \"BL\","); sb.Append("\"title\": \"生物\""); sb.Append("},"); sb.Append(" {"); sb.Append("\"code\": \"CP\","); sb.Append("\"title\": \"外文\""); sb.Append("},"); sb.Append("{"); sb.Append("\"code\": \"GP\","); sb.Append("\"title\": \"计算\""); sb.Append("}"); sb.Append("]"); List<CodeTitle> ctlist = Newtonsoft.Json.JsonConvert.DeserializeObject<List<CodeTitle>>(sb.ToString()); MessageBox.Show(ctlist.Count.ToString());//输出3 //此处会报错:电脑自动生成的对象并不全是对的。 Rootobject r = Newtonsoft.Json.JsonConvert.DeserializeObject<Rootobject>(sb.ToString()); } //自己手动写的:根据json格式的string解析的对象ClassObject和List class CodeTitle { public string code { get; set; } public string title { get; set; } } //电脑自动生成的Rootobject和Class1 public class Rootobject { public Class1[] Property1 { get; set; } } public class Class1 { public string code { get; set; } public string title { get; set; } }
完!
以上是关于将json格式的string转化为对象的主要内容,如果未能解决你的问题,请参考以下文章
arrayToJson将数组转化为json格式的js代码 ///////////////////////zzzzzzzzzzzzzzzz