[转]C# JSON格式的字符串读取到类中

将JSON格式的字符串读取到类中

本例中建立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; //成就

            //构造函数
            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();
        }
    }
}

运行结果:

END

 

转载于:https://www.cnblogs.com/Raywang80s/p/6891301.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值