本文实例讲述了C#实现JSON和对象之间互相转换功能。分享给大家供大家参考,具体如下:
1.首先是声明用户信息对象,DataContract修饰类,表示可以被解析成JSON,DataMember修饰属性,Order表示 解析的顺序,另外Lover是数组列表,表示女朋友个数
Address 表示送货地址,DailyRecord 表示日常记录
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.Serialization; namespace FunctionTest.Model { [DataContract] public class UserInfo { [DataMember(Order =0)] public string UserName { get; set; } [DataMember(Order = 1)] public int Age { get; set; } [DataMember(Order = 2)] public int Gender { get; set; } [DataMember(Order =3)] public ListLover { get; set; } [DataMember(Order = 4)] public ContactAddress Address { get; set; } [DataMember(Order = 5)] public Dictionary DailyRecord { get; set; } } [DataContract] public class ContactAddress { [DataMember(Order =0)] public string Province { get; set; } [DataMember(Order = 1)] public string City { get; set; } [DataMember(Order = 2)] public string Country { get; set; } [DataMember(Order = 3)] public string Details { get; set; } } }
2.JSON帮助类 核心代码
////// Json转换成对象 /// ////// /// public static T JsonToObject (string jsonText) { DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(T)); MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonText)); T obj = (T)s.ReadObject(ms); ms.Dispose(); return obj; } /// /// 对象转换成JSON /// ////// /// public static string ObjectToJSON (T obj) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T)); string result = string.Empty; using (MemoryStream ms = new MemoryStream()) { serializer.WriteObject(ms, obj); ms.Position = 0; using (StreamReader read = new StreamReader(ms)) { result = read.ReadToEnd(); } } return result; }
3.调用
//1.对象-->JSON UserInfo info = new UserInfo { Age = 10, Gender = 1, UserName = "刘德华", Lover = new List{ "美女1", "美女2", "美女3" }, Address = new ContactAddress { Province = "湖南省", City = "长沙市", Country = "望城县", Details = "某旮旯快递找不到的地方" }, DailyRecord = new Dictionary { { "星期一", "吃饭" }, { "星期二", "洗衣服" }, { "星期三", "好事情" } } }; string json = 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/json
JSON在线格式化工具:
http://tools.jb51.net/code/jsonformat
在线XML/JSON互相转换工具:
http://tools.jb51.net/code/xmljson
json代码在线格式化/美化/压缩/编辑/转换工具:
http://tools.jb51.net/code/jsoncodeformat
在线json压缩/转义工具:
http://tools.jb51.net/code/json_yasuo_trans
更多关于C#相关内容还可查看本站专题:《C#字符串操作技巧总结》、《C#常见控件用法教程》、《WinForm控件用法总结》、《C#程序设计之线程使用技巧总结》、《C#中XML文件操作技巧汇总》、《C#数据结构与算法教程》、《C#数组操作技巧总结》及《C#面向对象程序设计入门教程》
希望本文所述对大家C#程序设计有所帮助。