C#實(shí)現(xiàn)將類的內(nèi)容寫成JSON格式字符串的方法
本文實(shí)例講述了C#實(shí)現(xiàn)將類的內(nèi)容寫成JSON格式字符串的方法。分享給大家供大家參考。具體如下:
本例中建立了Person類,賦值后將類中內(nèi)容寫入到字符串中
運(yùn)行本代碼需要添加引用動(dòng)態(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è)置一個(gè)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");
//縮進(jìn)輸出
Console.WriteLine("Formatting.Indented:");
string json2 = JsonConvert.SerializeObject(p, Formatting.Indented);
Console.WriteLine(json2 + "\n");
Console.ReadLine();
}
}
}
運(yùn)行結(jié)果:

希望本文所述對(duì)大家的C#程序設(shè)計(jì)有所幫助。
- C#、.Net中把字符串(String)格式轉(zhuǎn)換為DateTime類型的三種方法
- C#中使用強(qiáng)制類型實(shí)現(xiàn)字符串和ASCII碼之間的轉(zhuǎn)換
- C#實(shí)現(xiàn)實(shí)體類與字符串互相轉(zhuǎn)換的方法
- C#生成不重復(fù)隨機(jī)字符串類
- C#實(shí)現(xiàn)的字符串相似度對(duì)比類
- c#字符串值類型與引用類型比較示例
- C#字符串的常用操作工具類代碼分享
- 在C#及.NET框架中使用StringBuilder類操作字符串的技巧
- C#實(shí)現(xiàn)簡(jiǎn)易的加密、解密字符串工具類實(shí)例
- 非常實(shí)用的C#字符串操作處理類StringHelper.cs
相關(guān)文章
WPF+SkiaSharp實(shí)現(xiàn)自繪拖曳小球
WPF的拖曳效果,基本配置一下,就可以了,但是自繪的話,就得自己控制。本文將利用WPF+SkiaSharp實(shí)現(xiàn)自繪拖曳小球,感興趣的可以動(dòng)手嘗試一下2022-07-07
C#基于Socket套接字的網(wǎng)絡(luò)通信封裝
這篇文章主要為大家詳細(xì)介紹了C#基于Socket套接字的網(wǎng)絡(luò)通信封裝本文實(shí)例為大家分享了Java實(shí)現(xiàn)圖片旋轉(zhuǎn)的具體代碼,供大家參考,具體內(nèi)容如下2021-11-11
C#日期格式強(qiáng)制轉(zhuǎn)換方法(推薦)
下面小編就為大家分享一C#日期格式強(qiáng)制轉(zhuǎn)換的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2017-11-11
Unity實(shí)現(xiàn)簡(jiǎn)易日志輸出功能
這篇文章主要為大家詳細(xì)介紹了Unity實(shí)現(xiàn)簡(jiǎn)易日志輸出功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-09-09
DevExpress實(shí)現(xiàn)為TextEdit設(shè)置水印文字的方法
這篇文章主要介紹了DevExpress實(shí)現(xiàn)為TextEdit設(shè)置水印文字的方法,對(duì)C#程序設(shè)計(jì)人員來說是一個(gè)很實(shí)用的技巧,需要的朋友可以參考下2014-08-08
C#的File類實(shí)現(xiàn)文件操作實(shí)例詳解
這篇文章主要介紹了C#的File類實(shí)現(xiàn)文件操作的方法,非常實(shí)用,需要的朋友可以參考下2014-07-07

