C#序列化和反序列化json

来源:互联网 发布:知乎无法复制 编辑:程序博客网 时间:2024/06/06 14:24

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);//反序列化1string desJson = jsonData;ModelDes model = js.Deserialize(desJson);//反序列化2dynamic 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

原创粉丝点击