[转]C# JSON格式的字符串读取到类中
Posted 精细化设计
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[转]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
以上是关于[转]C# JSON格式的字符串读取到类中的主要内容,如果未能解决你的问题,请参考以下文章
JQuery .ajax 返回json格式,浏览器显示带有转义字符问题
c# 拼接字符串并转化为json数据时,总是无法转到所需格式