作者:王選易,出處:http://www.survivalescaperooms.com/neverdie/ 歡迎轉(zhuǎn)載,也請(qǐng)保留這段聲明。如果你喜歡這篇文章,請(qǐng)點(diǎn)【推薦】。謝謝!
JSON是一個(gè)簡(jiǎn)單的,但功能強(qiáng)大的序列化數(shù)據(jù)格式。它定義了簡(jiǎn)單的類(lèi)型,如布爾,數(shù)(int和float)和字符串,和幾個(gè)數(shù)據(jù)結(jié)構(gòu):list和dictionnary。可以在http://JSON.org了解關(guān)于JSON的更多信息。
litjson是用C #編寫(xiě)的,它的目的是要小,快速,易用。它使用了Mono框架。
將LitJSON編譯好的dll文件通過(guò)Import New Asset的方式導(dǎo)入到項(xiàng)目中,再使用Using LitJSON即可使用JSONMapper類(lèi)中的簡(jiǎn)便方法。dll的下載地址在這里.
為了在.Net程序中使用JSON格式的數(shù)據(jù)。一個(gè)自然的方法是使用JSON文本生成一個(gè)特定的類(lèi)的一個(gè)新實(shí)例;為了匹配類(lèi)的格式,一般存儲(chǔ)的JSON字符串是一個(gè)字典。
另一方面,為了將對(duì)象序列化為JSON字符串,一個(gè)簡(jiǎn)單的導(dǎo)出操作,聽(tīng)起來(lái)是個(gè)好主意。
為了這個(gè)目的,LitJSON包引入了JsonMapper類(lèi),它提供了兩個(gè)用于做到 JSON轉(zhuǎn)化為object 和 object轉(zhuǎn)化為JSON 的主要方法。這兩個(gè)方法是jsonmapper.toobject和jsonmapper.tojson。
將object轉(zhuǎn)化為字符串之后,我們就可以將這個(gè)字符串很方便地在文件中讀取和寫(xiě)入了。
在下面的例子中,ToObject方法有一個(gè)泛型參數(shù),來(lái)指定返回的某種特定的數(shù)據(jù)類(lèi)型:即JsonMapper.ToObject<T>。
using LitJson;using System;public class Person{ // C# 3.0 auto-implemented PRoperties public string Name { get; set; } public int Age { get; set; } public DateTime Birthday { get; set; }}public class JsonSample{ public static void Main() { PersonToJson(); JsonToPerson(); } public static void PersonToJson() { Person bill = new Person(); bill.Name = "William Shakespeare"; bill.Age = 51; bill.Birthday = new DateTime(1564, 4, 26); string json_bill = JsonMapper.ToJson(bill); Console.WriteLine(json_bill); } public static void JsonToPerson() { string json = @" { ""Name"" : ""Thomas More"", ""Age"" : 57, ""Birthday"" : ""02/07/1478 00:00:00"" }"; Person thomas = JsonMapper.ToObject<Person>(json); Console.WriteLine("Thomas' age: {0}", thomas.Age); }}
上文的輸出:
{"Name":"William Shakespeare","Age":51,"Birthday":"04/26/1564 00:00:00"}Thomas' age: 57
當(dāng)不存在特定的JSON數(shù)據(jù)類(lèi)時(shí),它將返回一個(gè)JSONData實(shí)例。JSONData是一種通用型可以保存任何數(shù)據(jù)類(lèi)型支持JSON,包括list和dictionary。
using LitJson;using System;public class JsonSample{ public static void Main() { string json = @" { ""album"" : { ""name"" : ""The Dark Side of the Moon"", ""artist"" : ""Pink Floyd"", ""year"" : 1973, ""tracks"" : [ ""Speak To Me"", ""Breathe"", ""On The Run"" ] } } "; LoadAlbumData(json); } public static void LoadAlbumData(string json_text) { Console.WriteLine("Reading data from the following JSON string: {0}", json_text); JsonData data = JsonMapper.ToObject(json_text); // Dictionaries are accessed like a hash-table Console.WriteLine("Album's name: {0}", data["album"]["name"]); // Scalar elements stored in a JsonData instance can be cast to // their natural types string artist = (string) data["album"]["artist"]; int year = (int) data["album"]["year"]; Console.WriteLine("Recorded by {0} in {1}", artist, year); // Arrays are accessed like regular lists as well Console.WriteLine("First track: {0}", data["album"]["tracks"][0]); }}
上面例子的輸出:
Reading data from the following JSON string: { "album" : { "name" : "The Dark Side of the Moon", "artist" : "Pink Floyd", "year" : 1973, "tracks" : [ "Speak To Me", "Breathe", "On The Run" ] } }Album's name: The Dark Side of the MoonRecorded by Pink Floyd in 1973First track: Speak To Me
一些人喜歡使用stream的方式處理JSON數(shù)據(jù),對(duì)于他們, 我們提供的接口是jsonreader和jsonwriter。
JSONMapper實(shí)際上是建立在以上兩個(gè)類(lèi)的基礎(chǔ)上的,所以你可以把這兩個(gè)類(lèi)當(dāng)成是litJSON的底層接口。
using LitJson;using System;public class DataReader{ public static void Main() { string sample = @"{ ""name"" : ""Bill"", ""age"" : 32, ""awake"" : true, ""n"" : 1994.0226, ""note"" : [ ""life"", ""is"", ""but"", ""a"", ""dream"" ] }"; PrintJson(sample); } public static void PrintJson(string json) { JsonReader reader = new JsonReader(json); Console.WriteLine ("{0,14} {1,10} {2,16}", "Token", "Value", "Type"); Console.WriteLine (new String ('-', 42)); // The Read() method returns false when there's nothing else to read while (reader.Read()) { string type = reader.Value != null ? reader.Value.GetType().ToString() : ""; Console.WriteLine("{0,14} {1,10} {2,16}", reader.Token, reader.Value, type); } }}
輸出如下:
Token Value Type------------------------------------------ ObjectStart PropertyName name System.String String Bill System.String PropertyName age System.String Int 32 System.Int32 PropertyName awake System.String Boolean True System.Boolean PropertyName n System.String Double 1994.0226 System.Double PropertyName note System.String ArrayStart String life System.String String is System.String String but System.String String a System.String String dream System.String ArrayEnd ObjectEnd
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注