C#序列化和反序列化json

本文介绍JSON格式的特点及其实现序列化和反序列化的两种方法:使用JavaScriptSerializer和Json.NET库。通过实例展示了如何将对象转换为JSON字符串以及如何从JSON字符串还原对象。

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write and easy for machines to parse and generate. JSON is a text format that is completely language independent. 

json是一个轻量级的数据交换格式,我们可以很简单的来读取和写它,并且它很容易被计算机转化和生成,它是完全独立于语言的。


使用JavaScriptJsonSerializer实现序列化和反序列化

//使用JavaScriptSerializer方式需要引入的命名空间,这个在程序集System.Web.Extensions.dll.中
using System.Web.Script.Serialization;
//序列化
class ModelDes
{
    public string name { get; set; }
    public string des { get; set; }
}
ModelDes model = new ModelDes();
model.name = "testModel";
model.des = "testModel";
string jsonData = js.Serialize(model);
//反序列化1
string desJson = jsonData;
ModelDes model = js.Deserialize
   
    (desJson);
//反序列化2
dynamic modeldy = js.Deserialize
    
     (desJson);
string messageDy = string.Format("动态的反序列化,name={0},des={1}",
                modelDy["name"], modelDy["des"]);//这里要使用索引取值,不能使用对象.属性
    
   

使用JSON.NET实现序列化和反序列化

Json.NET is a third party library which helps conversion between JSON text and .NET object using the JsonSerializer. The JsonSerializer converts .NET objects into their JSON equivalent text and back again by mapping the .NET object property names to the JSON property names. It is open source software and free for commercial purposes.

In Visual Studio, go to Tools Menu -> Choose Library Package Manger -> Package Manager Console. It opens a command window where we need to put the following command to install Newtonsoft.Json. 
Install-Package Newtonsoft.Json
OR
In Visual Studio, Tools menu -> Manage Nuget Package Manger Solution and type “JSON.NET” to search it online. 

这里代码引用自

http://www.cnblogs.com/caofangsheng/p/5687994.html

//使用Json.NET类库需要引入的命名空间
//-----------------------------------------------------------------------------
using Newtonsoft.Json;
//-------------------------------------------------------------------------
#region 3.Json.NET序列化
List
   
     lstStuModel = new List
    
     () 
{
    new Student(){ID=1,Name="张飞",Age=250,Sex="男"},
    new Student(){ID=2,Name="潘金莲",Age=300,Sex="女"}
};

//Json.NET序列化
string jsonData = JsonConvert.SerializeObject(lstStuModel);
Console.WriteLine(jsonData);
Console.ReadKey();


//Json.NET反序列化
string json = @"{ 'Name':'C#','Age':'3000','ID':'1','Sex':'女'}";
Student descJsonStu = JsonConvert.DeserializeObject
     
      (json);//反序列化
Console.WriteLine(string.Format("反序列化: ID={0},Name={1},Sex={2},Sex={3}", descJsonStu.ID, descJsonStu.Name, descJsonStu.Age, descJsonStu.Sex));
Console.ReadKey(); 
#endregion
     
    
   

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值