参考
C#中Json序列化和反序列化总结
JavaScriptSerialize
创建实体类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Serializer
{
public class UserInfo
{
///
/// 编号
///
public int ID { get; set; }
///
/// 名称
///
public string Name { get; set; }
///
/// 创建时间
///
public DateTime? CreateTime { get; set; }
public UserInfo() { }
public UserInfo(int id, string name, DateTime? createTime = null)
{
this.ID = id;
this.Name = name;
this.CreateTime = createTime;
}
}
}
测试
using Nancy.Json;
using Serializer;
List userList = new List();
userList.Add(new UserInfo() { ID = 1, Name = "张三", CreateTime = DateTime.Now });
userList.Add(new UserInfo() { ID = 2, Name = "李四", CreateTime = DateTime.Now });
userList.Add(new UserInfo() { ID = 2, Name = "王五" });
//创建一个JavaScriptSerializer对象
JavaScriptSerializer serializer = new JavaScriptSerializer();
//将用户列表序列化成JSON
string serializedResult = serializer.Serialize(userList);
Console.WriteLine(serializedResult);
//将JOSN反序列化成用户列表
List deserializeResult = serializer.Deserialize(serializedResult);
Console.WriteLine(deserializeResult[0].Name);
Console.WriteLine(deserializeResult[0].CreateTime);
Console.ReadLine();
DataContractJsonSerializer
创建实体类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace DataContractJsonSerializer1
{
[DataContract]
public class Order
{
private List items;
public Order()
{
}
public Order(int id, DateTime orderDate, bool useCoupon)
{
this.ID = id;
this.OrderDate = orderDate;
this.UseCoupon = useCoupon;
this.items = new List();
}
[DataMember]
public int ID { get; set; }
[DataMember]
public DateTime OrderDate { get; set; }
[DataMember]
public bool UseCoupon { get; set; }
[DataMember]
public List Items
{
get { return items; }
set { items = value; }
}
}
[DataContract]
public class OrderItem
{
public OrderItem(Product product, int count)
{
this.Product = product;
this.Count = count;
}
[DataMember]
public Product Product { get; set; }
[DataMember]
public int Count { get; set; }
}
[DataContract]
public class Product
{
public Product(string name, double price)
{
this.Name = name;
this.Price = price;
}
[DataMember]
public string Name { get; set; }
[DataMember]
public double Price { get; set; }
}
}
创建工具类
using System.Text;
using System.Runtime.Serialization.Json;
namespace DataContractJsonSerializer1
{
public class JsonHelper
{
public static string Serialize(T obj)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
using (MemoryStream ms = new MemoryStream())
{
serializer.WriteObject(ms, obj);
string retVal = Encoding.UTF8.GetString(ms.ToArray());
return retVal;
}
}
public static T Deserialize(string json)
{
T obj = Activator.CreateInstance();
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
obj = (T)serializer.ReadObject(ms);
ms.Close();
ms.Dispose();
return obj;
}
}
}
测试
using DataContractJsonSerializer1;
///序列化
Order order = new Order(1, DateTime.Now, true);
order.Items.Add(new OrderItem(new Product("笔记本", 3000), 2));
order.Items.Add(new OrderItem(new Product("无线键鼠", 126.9), 2));
string jsonStr = JsonHelper.Serialize(order);
Console.WriteLine("rn序列化得到Json字符串:rn");
Console.WriteLine(jsonStr);
///反序列化
Order dOrder = JsonHelper.Deserialize(jsonStr);
Console.WriteLine("rnrn反序列化结果:");
Console.WriteLine("rnOrderID: " + dOrder.ID.ToString());
Console.WriteLine("rnOrderDate: " + dOrder.OrderDate.ToString("yyyy/MM/dd HH:mm:ss"));
Console.WriteLine("rnUseCoupon: " + dOrder.UseCoupon.ToString());
foreach (OrderItem item in dOrder.Items)
{
Console.WriteLine("rn==========================");
Console.WriteLine("rnProduct name: " + item.Product.Name);
Console.WriteLine("rnPrice: " + item.Product.Price.ToString());
Console.WriteLine("rnCount: " + item.Count.ToString());
}
Console.ReadLine();
Newtonsoft.Json
依赖下载
Newtonsoft.Json
测试
using Newtonsoft.Json;
using System.Data;
DataTable dt = new DataTable();
dt.Columns.Add("Age", Type.GetType("System.Int32"));
dt.Columns.Add("Name", Type.GetType("System.String"));
dt.Columns.Add("Sex", Type.GetType("System.String"));
dt.Columns.Add("IsMarry", Type.GetType("System.Boolean"));
for (int i = 0; i 0 ? true : false;
dt.Rows.Add(dr);
}
string dejsonstr = JsonConvert.SerializeObject(dt);
Console.WriteLine("rn序列化得到Json字符串:rn");
Console.WriteLine(dejsonstr);
///反序列化
Console.WriteLine("rnrn反序列化结果:");
dt = JsonConvert.DeserializeObject(dejsonstr);
foreach (DataRow dr in dt.Rows)
{
Console.WriteLine("{0}t{1}t{2}t{3}t", dr[0], dr[1], dr[2], dr[3]);
}
Console.ReadLine();