C#实现JSON和对象之间互相转换功能示例
本文实例讲述了C#实现JSON和对象之间互相转换功能。分享给大家供大家参考,具体如下:
1.首先是声明用户信息对象,DataContract修饰类,表示可以被解析成JSON,DataMember修饰属性,Order表示解析的顺序,另外Lover是数组列表,表示女朋友个数
Address表示送货地址,DailyRecord 表示日常记录
usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; usingSystem.Runtime.Serialization; namespaceFunctionTest.Model { [DataContract] publicclassUserInfo { [DataMember(Order=0)] publicstringUserName{get;set;} [DataMember(Order=1)] publicintAge{get;set;} [DataMember(Order=2)] publicintGender{get;set;} [DataMember(Order=3)] publicListLover{get;set;} [DataMember(Order=4)] publicContactAddressAddress{get;set;} [DataMember(Order=5)] publicDictionary DailyRecord{ get;set; } } [DataContract] publicclassContactAddress { [DataMember(Order=0)] publicstringProvince{get;set;} [DataMember(Order=1)] publicstringCity{get;set;} [DataMember(Order=2)] publicstringCountry{get;set;} [DataMember(Order=3)] publicstringDetails{get;set;} } }
2.JSON帮助类核心代码
//////Json转换成对象 /// ////// /// publicstaticTJsonToObject (stringjsonText) { DataContractJsonSerializers=newDataContractJsonSerializer(typeof(T)); MemoryStreamms=newMemoryStream(Encoding.UTF8.GetBytes(jsonText)); Tobj=(T)s.ReadObject(ms); ms.Dispose(); returnobj; } /// ///对象转换成JSON /// ////// /// publicstaticstringObjectToJSON (Tobj) { DataContractJsonSerializerserializer=newDataContractJsonSerializer(typeof(T)); stringresult=string.Empty; using(MemoryStreamms=newMemoryStream()) { serializer.WriteObject(ms,obj); ms.Position=0; using(StreamReaderread=newStreamReader(ms)) { result=read.ReadToEnd(); } } returnresult; }
3.调用
//1.对象-->JSON UserInfoinfo=newUserInfo { Age=10, Gender=1, UserName="刘德华", Lover=newList{"美女1","美女2","美女3"}, Address=newContactAddress { Province="湖南省", City="长沙市", Country="望城县", Details="某旮旯快递找不到的地方" }, DailyRecord=newDictionary {{"星期一","吃饭"},{"星期二","洗衣服"},{"星期三","好事情"}} }; stringjson=ObjectToJSON (info);
4.反序列化后的结果
{"UserName":"刘德华","Age":10,"Gender":1,"Lover":["美女1","美女2","美女3"],"Address":{"Province":"湖南省","City":"长沙市","Country":"望城县","Details":"某旮旯快递找不到的地方"},"DailyRecord":[{"Key":"星期一","Value":"吃饭"},{"Key":"星期二","Value":"洗衣服"},{"Key":"星期三","Value":"好事情"}]}
PS:关于json操作,这里再为大家推荐几款比较实用的json在线工具供大家参考使用:
在线
JSON在线格式化工具:
http://tools.jb51.net/code/jsonformat
在线XML/