1. 程式人生 > >使用Newtonsoft.Json.dll(JSON.NET)動態解析JSON、.net 的json的序列化與反序列化(一)

使用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字串。


Newtonsoft.Json的地址:

例子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; }
    }
複製程式碼

執行結果: