C#中实现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【javascript对象表示方法】,它是一个轻量级的数据交换格式,我们可以很简单的来读取和写它,并且它很容易被计算机转化和生成,它是完全独立于语言的。
json支持下面两种数据结构:
- 键值对的集合--各种不同的编程语言,都支持这种数据结构;
- 有序的列表类型值的集合--这其中包含数组,集合,矢量,或者序列,等等。
json有下面几种表现形式
1.对象
一个没有顺序的“键/值”,一个对象以花括号“{”开始,并以花括号"}"结束,在每一个“键”的后面,有一个冒号,并且使用逗号来分隔多个键值对。
例如:
var user = {"name":"manas","gender":"male","birthday":"1987-8-8"}
2.数组
设置值的顺序,一个数组以中括号"["开始,并以中括号"]"结束,并且所有的值使用逗号分隔
例如:
var userlist = [{"user":{"name":"manas","gender":"male","birthday":"1987-8-8"}}, {"user":{"name":"mohapatra","male":"female","birthday":"1987-7-7"}}]
3.字符串
任意数量的unicode字符,使用引号做标记,并使用反斜杠来分隔。
例如:
var userlist = "{\"id\":1,\"name\":\"manas\",\"address\":\"india\"}"
好了,介绍完json,现在说正题。
序列化和反序列化有三种方式:
- 使用
javascriptserializer
类 - 使用
datacontractjsonserializer
类 - 使用json.net类库
我们先来看看使用 datacontractjsonserializer的情况
datacontractjsonserializer
类帮助我们序列化和反序列化json,他在程序集 system.runtime.serialization.dll
下的system.runtime.serialization.json
命名空间里。
首先,这里,我新建一个控制台的程序,新建一个类student
using system; using system.collections.generic; using system.linq; using system.text; using system.threading.tasks; using system.runtime.serialization; namespace jsonserializeranddeserializer { [datacontract] public class student { [datamember] public int id { get; set; } [datamember] public string name { get; set; } [datamember] public int age { get; set; } [datamember] public string sex { get; set; } } }
注意:上面的student实体中的契约 [datamember],[datacontract],是使用datacontractjsonserializer
序列化和反序列化必须要加的,对于其他两种方式不必加,也可以的。
我们程序的代码:
要先引用程序集,在引入这个命名空间
//---------------------------------------------------------------------------------------------- //使用datacontractjsonserializer方式需要引入的命名空间,在system.runtime.serialization.dll.中 using system.runtime.serialization.json; //--------------------------------------------------------------------------------------------
#region 1.datacontractjsonserializer方式序列化和反序列化 student stu = new student() { id = 1, name = "曹操", sex = "男", age = 1000 }; //序列化 datacontractjsonserializer js = new datacontractjsonserializer(typeof(student)); memorystream msobj = new memorystream(); //将序列化之后的json格式数据写入流中 js.writeobject(msobj, stu); msobj.position = 0; //从0这个位置开始读取流中的数据 streamreader sr = new streamreader(msobj, encoding.utf8); string json = sr.readtoend(); sr.close(); msobj.close(); console.writeline(json); //反序列化 string todes = json; //string to = "{\"id\":\"1\",\"name\":\"曹操\",\"sex\":\"男\",\"age\":\"1230\"}"; using (var ms = new memorystream(encoding.unicode.getbytes(todes))) { datacontractjsonserializer deseralizer = new datacontractjsonserializer(typeof(student)); student model = (student)deseralizer.readobject(ms);// //反序列化readobject console.writeline("id=" + model.id); console.writeline("name=" + model.name); console.writeline("age=" + model.age); console.writeline("sex=" + model.sex); } console.readkey(); #endregion
运行之后结果是:
再看看使用javascriptjsonserializer的情况:
javascriptserializer is a class which helps to serialize and deserialize json. it is present in namespace system.web.script.serialization which is available in assembly system.web.extensions.dll. to serialize a .net object to json string use serialize method. it's possible to deserialize json string to .net object using deserialize<t> or deserializeobject methods. let's see how to implement serialization and deserialization using javascriptserializer.
这里要先引用
//----------------------------------------------------------------------------------------- //使用javascriptserializer方式需要引入的命名空间,这个在程序集system.web.extensions.dll.中 using system.web.script.serialization; //----------------------------------------------------------------------------------------
#region 2.javascriptserializer方式实现序列化和反序列化 student stu = new student() { id = 1, name = "关羽", age = 2000, sex = "男" }; javascriptserializer js = new javascriptserializer(); string jsondata = js.serialize(stu);//序列化 console.writeline(jsondata); ////反序列化方式一: string desjson = jsondata; //student model = js.deserialize<student>(desjson);// //反序列化 //string message = string.format("id={0},name={1},age={2},sex={3}", model.id, model.name, model.age, model.sex); //console.writeline(message); //console.readkey(); ////反序列化方式2 dynamic modeldy = js.deserialize<dynamic>(desjson); //反序列化 string messagedy = string.format("动态的反序列化,id={0},name={1},age={2},sex={3}", modeldy["id"], modeldy["name"], modeldy["age"], modeldy["sex"]);//这里要使用索引取值,不能使用对象.属性 console.writeline(messagedy); console.readkey(); #endregion
结果是:
最后看看使用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.
the following are some awesome【极好的】 features,
flexible json serializer for converting between .net objects and json.
linq to json for manually reading and writing json.
high performance, faster than .net's built-in【内嵌】 json serializers.
easy to read json.
convert json to and from xml.
supports .net 2, .net 3.5, .net 4, silverlight and windows phone.
let's start learning how to install and implement:
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. here's the figure,
//使用json.net类库需要引入的命名空间 //----------------------------------------------------------------------------- using newtonsoft.json; //-------------------------------------------------------------------------
#region 3.json.net序列化 list<student> lststumodel = new list<student>() { 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<student>(json);//反序列化 console.writeline(string.format("反序列化: id={0},name={1},sex={2},sex={3}", descjsonstu.id, descjsonstu.name, descjsonstu.age, descjsonstu.sex)); console.readkey(); #endregion
运行之后,结果是:
总结
最后还是尽量使用json.net来序列化和反序列化,性能好。
in this article we discussed about how many ways we can implement serialization/deserialization in c#. however json.net wins over other implementations because it facilitates more functionality of json validation, json schema, linq to json etc. so use json.net always.
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。