C#如何?JSON與對象之間互相轉換功能樣本

來源:互聯網
上載者:User
這篇文章主要介紹了C#實現JSON和對象之間互相轉換功能,結合執行個體形式較為詳細的分析了C#實現對象與json之間相互轉換的操作技巧,需要的朋友可以參考下

本文執行個體講述了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 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轉換成對象/// </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>/// 對象轉換成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.調用


//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.還原序列化後的結果

代碼如下:

{"UserName":"劉德華","Age":10,"Gender":1,"Lover":["美女1","美女2","美女3"],"Address":{"Province":"湖南省","City":"長沙市","Country":"望城縣","Details":"某旮旯快遞找不到的地方"},"DailyRecord":[{"Key":"星期一","Value":"吃飯"},{"Key":"星期二","Value":"洗衣服"},{"Key":"星期三","Value":"好事情"}]}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.