本文實例講述了C#實現(xiàn)JSON和對象之間互相轉(zhuǎn)換功能。分享給大家供大家參考,具體如下:
1.首先是聲明用戶信息對象,DataContract修飾類,表示可以被解析成JSON,DataMember修飾屬性,Order表示 解析的順序,另外Lover是數(shù)組列表,表示女朋友個數(shù)
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 List<string> Lover { get; set; } [DataMember(Order = 4)] public ContactAddress Address { get; set; } [DataMember(Order = 5)] public Dictionary<string, string> 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幫助類 核心代碼
/// <summary>/// Json轉(zhuǎn)換成對象/// </summary>/// <typeparam name="T"></typeparam>/// <param name="jsonText"></param>/// <returns></returns>public static T JsonToObject<T>(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;}/// <summary>/// 對象轉(zhuǎn)換成JSON/// </summary>/// <typeparam name="T"></typeparam>/// <param name="obj"></param>/// <returns></returns>public static string ObjectToJSON<T>(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.調(diào)用
//1.對象-->JSONUserInfo info = new UserInfo{ Age = 10, Gender = 1, UserName = "劉德華", Lover = new List<string> { "美女1", "美女2", "美女3" }, Address = new ContactAddress { Province = "湖南省", City = "長沙市", Country = "望城縣", Details = "某旮旯快遞找不到的地方" }, DailyRecord = new Dictionary<string, string> { { "星期一", "吃飯" }, { "星期二", "洗衣服" }, { "星期三", "好事情" } }};string json = ObjectToJSON<UserInfo>(info);4.反序列化后的結(jié)果
PS:關(guān)于json操作,這里再為大家推薦幾款比較實用的json在線工具供大家參考使用:
在線JSON代碼檢驗、檢驗、美化、格式化工具:
http://tools.VeVB.COm/code/json
JSON在線格式化工具:
http://tools.VeVB.COm/code/jsonformat
在線XML/JSON互相轉(zhuǎn)換工具:
http://tools.VeVB.COm/code/xmljson
json代碼在線格式化/美化/壓縮/編輯/轉(zhuǎn)換工具:
http://tools.VeVB.COm/code/jsoncodeformat
在線json壓縮/轉(zhuǎn)義工具:
http://tools.VeVB.COm/code/json_yasuo_trans
更多關(guān)于C#相關(guān)內(nèi)容還可查看本站專題:《C#字符串操作技巧總結(jié)》、《C#常見控件用法教程》、《WinForm控件用法總結(jié)》、《C#程序設(shè)計之線程使用技巧總結(jié)》、《C#中XML文件操作技巧匯總》、《C#數(shù)據(jù)結(jié)構(gòu)與算法教程》、《C#數(shù)組操作技巧總結(jié)》及《C#面向?qū)ο蟪绦蛟O(shè)計入門教程》
希望本文所述對大家C#程序設(shè)計有所幫助。
新聞熱點
疑難解答
圖片精選