标签:email img bre 需要 code set generic namespace reading
首先理解,json是一种数据格式,而非一种数据类型。json格式的数据类型在c#中为string
开始测试:
使用Newtonsoft.Json包
一:json转object
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JsonTest { class Program { static void Main(string[] args) {
//构造json字符串 var json = "{ ‘people‘:" + "[{ ‘firstName‘: ‘Brett‘, ‘lastName‘:‘McLaughlin‘, ‘email‘: ‘aaaa‘ }," + "{ ‘firstName‘: ‘Jason‘, ‘lastName‘:‘Hunter‘, ‘email‘: ‘bbbb‘}," + "{ ‘firstName‘: ‘Elliotte‘, ‘lastName‘:‘Harold‘, ‘email‘: ‘cccc‘ }]}";
//使用Newtonsoft.Json中的JsonConvert转换json var jsonObj = JsonConvert.DeserializeObject<PeopleFather>(json); foreach (People item in jsonObj.people) { Console.WriteLine("firstName:"+item.firstName); Console.WriteLine("lastName:" + item.lastName); Console.WriteLine("email:" + item.email); Console.WriteLine("------"); } Console.ReadLine(); } } //构造json要转换的类 public class PeopleFather { public List<People> people { get; set; } } public class People { public string firstName { get; set; } public string lastName { get; set; } public string email { get; set; } } }
结果:
二:对象类型转json
同样使用Newtonsoft.Json包
static void Main(string[] agrs) { var people = new People(); people.firstName = "a"; people.lastName = "b"; people.email = "c"; var json = JsonConvert.SerializeObject(people); Console.WriteLine(json); Console.ReadLine(); } public class People { public string firstName { get; set; } public string lastName { get; set; } public string email { get; set; } }
需要说明的是
JsonConvert.SerializeObjectzai 被多次重载,还提供其它很多功能的支持
标签:email img bre 需要 code set generic namespace reading
原文地址:http://www.cnblogs.com/ttkknetroad/p/7702740.html