C#實現(xiàn)將類的內(nèi)容寫成JSON格式字符串的方法
更新時間:2015年08月18日 12:43:08 作者:北風(fēng)其涼
這篇文章主要介紹了C#實現(xiàn)將類的內(nèi)容寫成JSON格式字符串的方法,涉及C#針對json格式數(shù)據(jù)轉(zhuǎn)換的相關(guān)技巧,具有一定參考借鑒價值,需要的朋友可以參考下
本文實例講述了C#實現(xiàn)將類的內(nèi)容寫成JSON格式字符串的方法。分享給大家供大家參考。具體如下:
本例中建立了Person類,賦值后將類中內(nèi)容寫入到字符串中
運行本代碼需要添加引用動態(tài)庫Newtonsoft.Json
程序代碼:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; //需要引用 Newtonsoft.Json.dll using Newtonsoft.Json; namespace JsonTest { class Program { /// <summary> /// 人員類 /// </summary> public class Person { public string name; //姓名 public int age; //年齡 public bool sex_is_male; //性別 public struct Partner //伙伴 { public string partner_name; //伙伴姓名 public int partner_age; //伙伴年齡 public bool partner_sex_is_male; //伙伴性別 } public Partner partner; public string[] achievement; //成就 } static void Main(string[] args) { //設(shè)置一個Person類 Person p = new Person(); p.name = "Tsybius"; p.age = 23; p.sex_is_male = true; p.partner.partner_name = "Galatea"; p.partner.partner_age = 21; p.partner.partner_sex_is_male = false; p.achievement = new string[] { "ach1", "ach2", "ach3" }; //直接輸出 Console.WriteLine("Formatting.None:"); string json1 = JsonConvert.SerializeObject(p); Console.WriteLine(json1 + "\n"); //縮進輸出 Console.WriteLine("Formatting.Indented:"); string json2 = JsonConvert.SerializeObject(p, Formatting.Indented); Console.WriteLine(json2 + "\n"); Console.ReadLine(); } } }
運行結(jié)果:
希望本文所述對大家的C#程序設(shè)計有所幫助。
相關(guān)文章
C#基于Socket套接字的網(wǎng)絡(luò)通信封裝
這篇文章主要為大家詳細介紹了C#基于Socket套接字的網(wǎng)絡(luò)通信封裝本文實例為大家分享了Java實現(xiàn)圖片旋轉(zhuǎn)的具體代碼,供大家參考,具體內(nèi)容如下2021-11-11DevExpress實現(xiàn)為TextEdit設(shè)置水印文字的方法
這篇文章主要介紹了DevExpress實現(xiàn)為TextEdit設(shè)置水印文字的方法,對C#程序設(shè)計人員來說是一個很實用的技巧,需要的朋友可以參考下2014-08-08