您的位置:首页 > Web前端 > JavaScript

使用Newtonsoft.Json.dll(JSON.NET)动态解析JSON、.net 的json的序列化与反序列化(一)

2016-11-26 01:02 886 查看
在开发中,我非常喜欢动态语言和匿名对象带来的方便,JSON.NET具有动态序列化和反序列化任意JSON内容的能力,不必将它映射到具体的强类型对象,它可以处理不确定的类型(集合、字典、动态对象和匿名对象),在这篇文章中我将通过JToken、JObject和JArray来动态解析JSON对象,使它很容易创建和检索的JSON内容而无需基础类型。通过JObject和JArray创建JSON对象我们先用非常简单的方法来动态创建一些JSON,可通过JToken派生的JSON.NET对象来进行,最常见的JToken派生的类是JObject和JArray。
因为JToken实现了IDynamicMetaProvider动态语言接口,所以可以使用dynamic关键字直观地创建动态对象,并把这个动态对象序列化为JSON字符串。

Newtonsoft.Json的地址:

官网:http://json.codeplex.com/

源码地址:https://github.com/JamesNK/Newtonsoft.Json

Newtonsoft.Json.dll下载:https://github.com/JamesNK/Newtonsoft.Json/releases

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

//Newtonsoft.Json.Linq.JObject jsonObject = new Newtonsoft.Json.Linq.JObject {{"Entered", DateTime.Now}};

Newtonsoft.Json.Linq.JObject jsonObject = new Newtonsoft.Json.Linq.JObject();

jsonObject.Add("Entered", DateTime.Now);

dynamic album = jsonObject;

album.AlbumName = "Dirty Deeds Done Dirt Cheap";
album.Artist = "AC/DC/DVD";
album.YearReleased = DateTime.Now.Year;

album.Songs = new Newtonsoft.Json.Linq.JArray() as dynamic;

dynamic song = new Newtonsoft.Json.Linq.JObject();
song.SongName = "Dirty Deeds Done Dirt Cheap";
song.SongLength = "4:05";
album.Songs.Add(song);

song = new Newtonsoft.Json.Linq.JObject();
song.SongName = "Love at First Feel";
song.SongLength = "3:01";
album.Songs.Add(song);

song = new Newtonsoft.Json.Linq.JObject();
song.SongName = "小苹果";
song.SongLength = "03:32";
album.Songs.Add(song);

Console.WriteLine(album.ToString());

Console.ReadLine();


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



例子2、

//Newtonsoft.Json.Linq.JObject jsonObject = new Newtonsoft.Json.Linq.JObject {{"Entered", DateTime.Now}};
Newtonsoft.Json.Linq.JObject jsonObject = new Newtonsoft.Json.Linq.JObject();
jsonObject.Add("Entered", DateTime.Now);
dynamic album = jsonObject;

album.AlbumName = "非主流歌曲";

foreach (var item in jsonObject)  //循环输出动态的值  JObject(基类为JContainer、JObject和JArray)是一个集合,实现了IEnumerable接口,因此你还可以轻松地在运行时循环访问
{
Console.WriteLine(item.Key + "的值为:" + item.Value.ToString());
}


执行结果为:



例子3:

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

var jsonString = @"{""Name"":""小苹果"",""Company"":""韩国公司"",   ""Entered"":""2016-11-26 00:14""}";

dynamic json = Newtonsoft.Json.Linq.JToken.Parse(jsonString) as dynamic;

string name = json.Name;
string company = json.Company;
DateTime entered = json.Entered;
Console.WriteLine("name:"+name);
Console.WriteLine("company:" + company);
Console.WriteLine("entered:" + entered);


执行结果:



例子4:

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

string jsonString1 = @"[{""Name"":""小苹果"",""Age"":""20""},{""Name"":""演员"",""Age"":""2""}]";
Newtonsoft.Json.Linq.JArray userAarray1 = Newtonsoft.Json.Linq.JArray.Parse(jsonString1) as Newtonsoft.Json.Linq.JArray;
List<User> userListModel = userAarray1.ToObject<List<User>>();
foreach (var userModel1 in userListModel)
{
Console.WriteLine("Name:" + userModel1.Name);
Console.WriteLine("Age:" + userModel1.Age);
}

Console.WriteLine("");
string jsonString = @"[{""Name"":""小苹果"",""Age"":""20""}]";
Newtonsoft.Json.Linq.JArray userAarray = Newtonsoft.Json.Linq.JArray.Parse(jsonString) as Newtonsoft.Json.Linq.JArray;
Newtonsoft.Json.Linq.JObject jObject = userAarray[0] as Newtonsoft.Json.Linq.JObject;
User userModel = jObject.ToObject<User>();
Console.WriteLine("Name:" + userModel.Name);
Console.WriteLine("Age:" + userModel.Age);


public class User
{
public string Name { set; get; }
public int Age { set; get; }
}


执行结果:



例子5、

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

UserType album = new UserType()
{
Type = "普通用户",
UserListModel = new List<User>()
{
new User()
{
Name="张三",
Age = 20
},
new User()
{
Name="李四",
Age = 30
}
}
};

// serialize to string
string json2 = Newtonsoft.Json.JsonConvert.SerializeObject(album, Newtonsoft.Json.Formatting.Indented);
Console.WriteLine("序列化结果");
Console.WriteLine("");
Console.WriteLine(json2);

UserType userType = Newtonsoft.Json.JsonConvert.DeserializeObject<UserType>(json2);
Console.WriteLine("");
Console.WriteLine("反序列化:");
Console.WriteLine("Type:"+ userType.Type);
Console.WriteLine("");
foreach (var userModel in userType.UserListModel)
{
Console.WriteLine("Name:"+userModel.Name);
Console.WriteLine("Age:" + userModel.Age);
}


public class UserType
{
public string Type { get; set; }
public List<User> UserListModel { get; set; }
}

public class User
{
public string Name { set; get; }
public int Age { set; get; }
}


执行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: