参考
JavaScriptSerialize
创建实体类
csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Serializer
{
public class UserInfo
{
/// <summary>
/// 编号
/// </summary>
public int ID { get; set; }
/// <summary>
/// 名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 创建时间
/// </summary>
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;
}
}
}
测试
ini
using Nancy.Json;
using Serializer;
List<UserInfo> userList = new List<UserInfo>();
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<UserInfo> deserializeResult = serializer.Deserialize<List<UserInfo>>(serializedResult);
Console.WriteLine(deserializeResult[0].Name);
Console.WriteLine(deserializeResult[0].CreateTime);
Console.ReadLine();
DataContractJsonSerializer
创建实体类
csharp
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<OrderItem> items;
public Order()
{
}
public Order(int id, DateTime orderDate, bool useCoupon)
{
this.ID = id;
this.OrderDate = orderDate;
this.UseCoupon = useCoupon;
this.items = new List<OrderItem>();
}
[DataMember]
public int ID { get; set; }
[DataMember]
public DateTime OrderDate { get; set; }
[DataMember]
public bool UseCoupon { get; set; }
[DataMember]
public List<OrderItem> 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; }
}
}
创建工具类
ini
using System.Text;
using System.Runtime.Serialization.Json;
namespace DataContractJsonSerializer1
{
public class JsonHelper
{
public static string Serialize<T>(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<T>(string json)
{
T obj = Activator.CreateInstance<T>();
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;
}
}
}
测试
swift
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>(order);
Console.WriteLine("\r\n序列化得到Json字符串:\r\n");
Console.WriteLine(jsonStr);
///反序列化
Order dOrder = JsonHelper.Deserialize<Order>(jsonStr);
Console.WriteLine("\r\n\r\n反序列化结果:");
Console.WriteLine("\r\nOrderID: " + dOrder.ID.ToString());
Console.WriteLine("\r\nOrderDate: " + dOrder.OrderDate.ToString("yyyy/MM/dd HH:mm:ss"));
Console.WriteLine("\r\nUseCoupon: " + dOrder.UseCoupon.ToString());
foreach (OrderItem item in dOrder.Items)
{
Console.WriteLine("\r\n==========================");
Console.WriteLine("\r\nProduct name: " + item.Product.Name);
Console.WriteLine("\r\nPrice: " + item.Product.Price.ToString());
Console.WriteLine("\r\nCount: " + item.Count.ToString());
}
Console.ReadLine();
Newtonsoft.Json
依赖下载
Newtonsoft.Json
测试
//序列化DataTable
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 < 4; i++)
{
DataRow dr = dt.NewRow();
dr["Age"] = i + 1;
dr["Name"] = "Name" + i;
dr["Sex"] = i % 2 == 0 ? "男" : "女";
dr["IsMarry"] = i % 2 > 0 ? true : false;
dt.Rows.Add(dr);
}
string dejsonstr = JsonConvert.SerializeObject(dt);
Console.WriteLine("\r\n序列化得到Json字符串:\r\n");
Console.WriteLine(dejsonstr);
///反序列化
Console.WriteLine("\r\n\r\n反序列化结果:");
dt = JsonConvert.DeserializeObject<DataTable>(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();