這篇文章主要介紹C#怎么實現(xiàn)JSON與對象之間互相轉換功能,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
創(chuàng)新互聯(lián)公司基于成都重慶香港及美國等地區(qū)分布式IDC機房數(shù)據中心構建的電信大帶寬,聯(lián)通大帶寬,移動大帶寬,多線BGP大帶寬租用,是為眾多客戶提供專業(yè)托管服務器報價,主機托管價格性價比高,為金融證券行業(yè)服務器托管,ai人工智能服務器托管提供bgp線路100M獨享,G口帶寬及機柜租用的專業(yè)成都idc公司。
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 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":"好事情"}]}
以上是C#怎么實現(xiàn)JSON與對象之間互相轉換功能的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注創(chuàng)新互聯(lián)行業(yè)資訊頻道!