将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 = ;
sex_is_male = true;
partner.partner_name = "";
partner.partner_age = ;
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