C# Newtonsoft.Json 应用

常用的一个简单方法

1 string jsonText = "{"zone":"海淀","zone_en":"haidian"}";
2 JObject jo = (JObject)JsonConvert.DeserializeObject(jsonText);
3 string zone = jo["zone"].ToString();
4 string zone_en = jo["zone_en"].ToString();

通过JArray和JObject来创建一个音乐专辑结构的一个示例:

 1   //Newtonsoft.Json.Linq.JObject jsonObject = new Newtonsoft.Json.Linq.JObject {{"Entered", DateTime.Now}};
 2 
 3             Newtonsoft.Json.Linq.JObject jsonObject = new Newtonsoft.Json.Linq.JObject();
 4 
 5             jsonObject.Add("Entered", DateTime.Now);
 6 
 7             dynamic album = jsonObject;
 8 
 9             album.AlbumName = "Dirty Deeds Done Dirt Cheap";
10             album.Artist = "AC/DC/DVD";
11             album.YearReleased = DateTime.Now.Year;
12 
13             album.Songs = new Newtonsoft.Json.Linq.JArray() as dynamic;
14 
15             dynamic song = new Newtonsoft.Json.Linq.JObject();
16             song.SongName = "Dirty Deeds Done Dirt Cheap";
17             song.SongLength = "4:05";
18             album.Songs.Add(song);
19 
20             song = new Newtonsoft.Json.Linq.JObject();
21             song.SongName = "Love at First Feel";
22             song.SongLength = "3:01";
23             album.Songs.Add(song);
24 
25             song = new Newtonsoft.Json.Linq.JObject();
26             song.SongName = "小苹果";
27             song.SongLength = "03:32";
28             album.Songs.Add(song);
29 
30             Console.WriteLine(album.ToString());
31 
32             Console.ReadLine();

以上代码最重要的是没有明确指定类型,便可将动态对象进行JSON序列化,而JObject对象只是接收数据,具体结构通过动态语言在运行时生成,这意味着此代码可以在运行时被编译,从而体现动态语言的优势。序列化的结果如下图所示:

 1  //Newtonsoft.Json.Linq.JObject jsonObject = new Newtonsoft.Json.Linq.JObject {{"Entered", DateTime.Now}};
 2             Newtonsoft.Json.Linq.JObject jsonObject = new Newtonsoft.Json.Linq.JObject();
 3             jsonObject.Add("Entered", DateTime.Now);
 4             dynamic album = jsonObject;
 5 
 6             album.AlbumName = "非主流歌曲";
 7 
 8             foreach (var item in jsonObject)  //循环输出动态的值  JObject(基类为JContainer、JObject和JArray)是一个集合,实现了IEnumerable接口,因此你还可以轻松地在运行时循环访问
 9             {
10                 Console.WriteLine(item.Key + "的值为:" + item.Value.ToString());
11             }

JObject.Parse()和JArray.Parse()方法导入JSON格式,JToken结构支持Parse()和Load()方法,这两个方法可以分别从字符串或各种流读取JSON数据。JValue包括最核心的JSON 解析能力,支持将字符串转化为我们熟悉的动态对象。将JSON字符串转换为成JObject对象,并强制转换为动态类型。

 1  var jsonString = @"{""Name"":""小苹果"",""Company"":""韩国公司"",   ""Entered"":""2016-11-26 00:14""}";
 2 
 3             dynamic json = Newtonsoft.Json.Linq.JToken.Parse(jsonString) as dynamic;
 4 
 5             string name = json.Name;
 6             string company = json.Company;
 7             DateTime entered = json.Entered;
 8             Console.WriteLine("name:" + name);
 9             Console.WriteLine("company:" + company);
10             Console.WriteLine("entered:" + entered);
11 
12             Console.ReadLine();

将JObject和JArray实例映射到一个强类型的对象,所以你可以在同一段代码中混合书写动态和静态类型

 1             string jsonString1 = @"[{""Name"":""小苹果"",""Age"":""20""},{""Name"":""演员"",""Age"":""2""}]";
 2             Newtonsoft.Json.Linq.JArray userAarray1 = Newtonsoft.Json.Linq.JArray.Parse(jsonString1) as Newtonsoft.Json.Linq.JArray;
 3             List<User> userListModel = userAarray1.ToObject<List<User>>();
 4             foreach (var userModel1 in userListModel)
 5             {
 6                 Console.WriteLine("Name:" + userModel1.Name);
 7                 Console.WriteLine("Age:" + userModel1.Age);
 8             }
 9 
10             Console.WriteLine("");
11             string jsonString = @"[{""Name"":""小苹果"",""Age"":""20""}]";
12             Newtonsoft.Json.Linq.JArray userAarray = Newtonsoft.Json.Linq.JArray.Parse(jsonString) as Newtonsoft.Json.Linq.JArray;
13             Newtonsoft.Json.Linq.JObject jObject = userAarray[0] as Newtonsoft.Json.Linq.JObject;
14             User userModel = jObject.ToObject<User>();
15             Console.WriteLine("Name:" + userModel.Name);
16             Console.WriteLine("Age:" + userModel.Age);
1 public class User
2     {
3         public string Name { set; get; }
4         public int Age { set; get; }
5     }

JSON.NET对动态语言的支持,但也别忘了它对静态类型的强大支持,关于如何序列化和反序列化强类型对象,JsonConvert是一个高级别的静态类,包装更低级别的功能,但你也可以使用JsonSerializer类,该类可以序列化和反序列化各种流

 1  UserType album = new UserType()
 2             {
 3                 Type = "普通用户",
 4                 UserListModel = new List<User>() 
 5                 {
 6                     new User()
 7                     {
 8                         Name="张三",
 9                         Age = 20
10                     },
11                     new User()
12                     {
13                         Name="李四",
14                         Age = 30
15                     }
16                 }
17             };
18 
19             // serialize to string            
20             string json2 = Newtonsoft.Json.JsonConvert.SerializeObject(album, Newtonsoft.Json.Formatting.Indented);
21             Console.WriteLine("序列化结果");
22             Console.WriteLine("");
23             Console.WriteLine(json2);
24 
25             UserType userType = Newtonsoft.Json.JsonConvert.DeserializeObject<UserType>(json2);
26             Console.WriteLine("");
27             Console.WriteLine("反序列化:");
28             Console.WriteLine("Type:"+ userType.Type);
29             Console.WriteLine("");
30             foreach (var userModel in userType.UserListModel)
31             {
32                 Console.WriteLine("Name:"+userModel.Name);
33                 Console.WriteLine("Age:" + userModel.Age);
34             }
 1  public class UserType
 2     {
 3         public string Type { get; set; }
 4         public List<User> UserListModel { get; set; }
 5     }
 6 
 7     public class User
 8     {
 9         public string Name { set; get; }
10         public int Age { set; get; }
11     }

 转自    http://www.cnblogs.com/linJie1930906722/p/6103455.html

原文地址:https://www.cnblogs.com/cwmizlp/p/9451103.html