C#完成將類的內容寫成JSON格局字符串的辦法。本站提示廣大學習愛好者:(C#完成將類的內容寫成JSON格局字符串的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是C#完成將類的內容寫成JSON格局字符串的辦法正文
本文實例講述了C#完成將類的內容寫成JSON格局字符串的辦法。分享給年夜家供年夜家參考。詳細以下:
本例中樹立了Person類,賦值後將類中內容寫入到字符串中
運轉本代碼須要添加援用靜態庫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)
{
//設置一個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();
}
}
}
運轉成果:

願望本文所述對年夜家的C#法式設計有所贊助。