码迷,mamicode.com
首页 > Windows程序 > 详细

C#将集合和Json格式互相转换的几种方式

时间:2016-02-03 18:11:08      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:

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格式互相转换的几种方式

标签:

原文地址:http://www.cnblogs.com/duanjt/p/5180164.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!