C# JSON格式的字符串讀取到類中

將JSON格式的字符串讀取到類中json

本例中創建JSON格式的字符串json,將其內容讀取到Person類中函數

運行本代碼須要添加引用動態庫Newtonsoft.Jsonspa

程序代碼:code

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; //成就

            //構造函數
            public Person()
            {
                name = "";
                age = 0;
                sex_is_male = true;
                partner.partner_name = "";
                partner.partner_age = 0;
                partner.partner_sex_is_male = true;
                achievement = null;
            }
        }

        static void Main(string[] args)
        {
            string json = string.Concat(
                "{",
                "    \"name\":\"Tsybius\",",
                "    \"age\":23,",
                "    \"sex_is_male\":true,",
                "    \"partner\":",
                "    {",
                "        \"partner_name\":\"Galatea\",",
                "        \"partner_age\":21,",
                "        \"partner_sex_is_male\":false",
                "    },",
                "    \"achievement\":[\"ach1\",\"ach2\",\"ach3\"]",
                "}"
            );

            //將內容賦值到Person類
            Person p = JsonConvert.DeserializeObject<Person>(json);
            Console.WriteLine("name: " + p.name);
            Console.WriteLine("age: " + p.age);
            Console.WriteLine("sex_is_male: " + p.sex_is_male);
            Console.WriteLine("partner_name: " + p.partner.partner_name);
            Console.WriteLine("partner_age: " + p.partner.partner_age);
            Console.WriteLine("partner_sex_is_male: " + p.partner.partner_sex_is_male);
            Console.Write("achievement: ");
            foreach (string achv in p.achievement)
            {
                Console.Write(achv + " ");
            }
            Console.WriteLine();

            Console.ReadLine();
        }
    }
}

運行結果:字符串

ENDstring

相關文章
相關標籤/搜索