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

在开发中,我很是喜欢动态语言和匿名对象带来的方便,JSON.NET具备动态序列化和反序列化任意JSON内容的能力,没必要将它映射到具体的强类型对象,它能够处理不肯定的类型(集合、字典、动态对象和匿名对象),在这篇文章中我将经过JToken、JObject和JArray来动态解析JSON对象,使它很容易建立和检索的JSON内容而无需基础类型。经过JObject和JArray建立JSON对象咱们先用很是简单的方法来动态建立一些JSON,可经过JToken派生的JSON.NET对象来进行,最多见的JToken派生的类是JObject和JArray。
由于JToken实现了IDynamicMetaProvider动态语言接口,因此可使用dynamic关键字直观地建立动态对象,并把这个动态对象序列化为JSON字符串。 git


Newtonsoft.Json的地址:github

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

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

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

例子一、
经过JArray和JObject来建立一个音乐专辑结构的一个示例:code

            //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对象只是接收数据,具体结构经过动态语言在运行时生成,这意味着此代码能够在运行时被编译,从而体现动态语言的优点。序列化的结果以下图所示:orm

例子二、对象

            //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());
            }

执行结果为:blog

例子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; }
    }

 

执行结果:

例子五、

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; }
    }

执行结果:

相关文章
相关标签/搜索