[轉]C# 將類的內容寫成JSON格式的字符串


將類的內容寫入到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();
        }
    }
}

運行結果:

END


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM