[转]C# 将类的内容写成JSON格式的字符串
生活随笔
收集整理的這篇文章主要介紹了
[转]C# 将类的内容写成JSON格式的字符串
小編覺得挺不錯的,現(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é)果:
END
轉(zhuǎn)載于:https://www.cnblogs.com/Raywang80s/p/6891292.html
總結(jié)
以上是生活随笔為你收集整理的[转]C# 将类的内容写成JSON格式的字符串的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: navicat 的查询功能
- 下一篇: 《Java技术》第九次作业计科1501赵