C#将集合和Json格式互相转换的几种方式
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#将集合和Json格式互相转换的几种方式相关的知识,希望对你有一定的参考价值。
1.使用微软自带的System.Web.Extensions.dll转换,该DLL文件一般存在于如下路径:c:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\System.Web.Extensions.dll
具体操作如下:
//将List集合转换为Json字符串,必须应用上面的DLL文件,同时引用using System.Web.Script.Serialization;命名空间 javascriptSerializer serializer = new JavaScriptSerializer(); List<Person> list = new List<Person>(); for (int i = 0; i < 10; i++) { Person p = new Person("张三" + i, "重庆" + i, "10" + i); list.Add(p); } MessageBox.Show(serializer.Serialize(list)); //将Json字符串转换为集合,Person为自己定义的实体类 string json = "[{‘Address‘:‘重庆0‘,‘Age‘:‘100‘,‘Name‘:‘张三0‘},{‘Address‘:‘重庆1‘,‘Age‘:‘101‘,‘Name‘:‘张三1‘}]"; JavaScriptSerializer serializer = new JavaScriptSerializer(); List<Person> list = serializer.Deserialize<List<Person>>(json);
2.可以借助开源的Newtonsoft.Json.dll进行转换
//将List集合转换为Json字符串 JavaScriptSerializer serializer = new JavaScriptSerializer(); List<Person> list = new List<Person>(); for (int i = 0; i < 10; i++) { Person p = new Person("张三" + i, "重庆" + i, "10" + i); list.Add(p); } MessageBox.Show(JsonConvert.SerializeObject(list)); //从JSON字符串生成集合对象 String json="[{\"Name\":\"张三0\",\"Address\":\"重庆0\",\"Age\":\"100\"},{\"Name\":\"张三1\",\"Address\":\"重庆1\",\"Age\":\"101\"}] "; var list=JsonConvert.DeserializeObject<Person>(json);
3.引用微软如下两个DLL
//注意引用:System.Runtime.Serialization,System.ServiceModel.Web // 从一个对象信息生成Json串 public static string ObjectToJson(object obj) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType()); MemoryStream stream = new MemoryStream(); serializer.WriteObject(stream, obj); byte[] dataBytes = new byte[stream.Length]; stream.Position = 0; stream.Read(dataBytes, 0, (int)stream.Length); return Encoding.UTF8.GetString(dataBytes); } // 从一个Json串生成对象信息 public static object JsonToObject(string jsonString, object obj) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType()); MemoryStream mStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)); return serializer.ReadObject(mStream); }
备注:
用到的类
public class Person { public String Name { get; set; } public String Address { get; set; } public int Age { get; set; } public Person() { } public Person(String name, String address, String age) { this.Name = name; this.Address = address; this.Age = age; } }
以上是关于C#将集合和Json格式互相转换的几种方式的主要内容,如果未能解决你的问题,请参考以下文章