.NET平臺開源JSON庫LitJSON的使用方法
一個簡單示例:
String str = "{’name’:’cyf’,’id’:10,’items’:[{’itemid’:1001,’itemname’:’hello’},{’itemid’:1002,’itemname’:’hello2’}]}";
// 讀取JSON字符串中的數據 **
JsonData jd = JsonMapper.ToObject(str);
String name = (String)jd["name"];
long id = (long)jd["id"];
JsonData jdItems = jd["items"];
int itemCnt = jdItems.Count; // 數組 items 中項的數量 foreach (JsonData item in jdItems) // 遍歷數組 items
{int itemID = (int)item["itemid"];
String itemName = (String)item["itemname"];
}// 將JsonData轉換為JSON字符串 **
String str2 = jd.ToJson();</pre>
下載地址 : 下載
LitJSON是一個.NET平臺下處理 JSON格式數據 的類庫,小巧、快速。它的源代碼使用C#編寫,可以通過任何.Net平臺上的語言進行調用,目前最新版本為LitJSON 0.5.0。
與以下這幾個.Net平臺上的開源JSON庫相比,LitJSON的性能遙遙領先:
Jayrock version 0.9.8316
LitJSON version 0.3.0
Newtonsoft Json.NET version 1.1
下面介紹LitJSON中常用的方法:
以下示例需要先添加引用LitJson.dll,再導入命名空間 using LitJson;
點擊直接下載 LitJSON.dll ,也可以到http://litjson.sourceforge.net去下載。
1、Json 與 C#中 實體對象 的相互轉換
例 1.1:使用 JsonMapper 類實現數據的轉換
ublic class Person { public string Name { get; set; } public int Age { get; set; } public DateTime Birthday { get; set; } } public class JsonSample { public static void Main() { PersonToJson(); JsonToPerson(); } /// /// 將實體類轉換成Json格式 /// public static void PersonToJson() { Person bill = new Person(); bill.Name = "www.87cool.com"; bill.Age = 3; bill.Birthday = new DateTime(2007, 7, 17); string json_bill = JsonMapper.ToJson(bill); Console.WriteLine(json_bill); //輸出:{"Name":"www.87cool.com","Age":3,"Birthday":"07/17/2007 00:00:00"} }/// /// 將Json數據轉換成實體類 /// public static void JsonToPerson() { string json = @" { ""Name"" : ""www.87cool.com"", ""Age"" : 3, ""Birthday"" : ""07/17/2007 00:00:00"" }"; Person thomas = JsonMapper.ToObject(json); Console.WriteLine("’87cool’ age: {0}", thomas.Age); //輸出:’87cool’ age: 3 } } </pre><br />
例 1.2:使用 JsonMapper 類將Json字符串轉換為C#認識的JsonData,再通過Json數據的屬性名或索引獲取其值。
在C#中讀取JsonData對象 和 在 JavaScript中讀取Json對像 的方法完全一樣;
對Json的這種讀取方式在C#中用起來非常爽,同時也很實用,因為現在很多網絡應用提供的API所返回的數據都是Json格式的,
如Flickr相冊API返回的就是json格式的數據。public static void LoadAlbumData(string json_text) { JsonData data = JsonMapper.ToObject(json_text); Console.WriteLine("Album’s name: {0}", data["album"]["name"]); string artist = (string)data["album"]["name"]; int year = (int)data["album"]["year"]; Console.WriteLine("First track: {0}", data["album"]["tracks"][0]); }
2、C# 中對 Json 的 Readers 和 Writers
例 2.1:JsonReader類的使用方法
public class DataReader { public static void Main () { string sample = @"{ ""name"" : ""Bill"", ""age"" : 32, ""awake"" : true, ""n"" : 1994.0226, ""note"" : [ ""life"", ""is"", ""but"", ""a"", ""dream"" ] }"; ReadJson (sample); } //輸出所有Json數據的類型和值 public static void ReadJson (string json) { JsonReader reader = new JsonReader (json);Console.WriteLine ("{0,14} {1,10} {2,16}", "Token", "Value", "Type"); Console.WriteLine (new String (’-’, 42)); 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); } }
} </pre>
//輸出結果:
// Json類型 值 C#類型
//------------------------------------------
// 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
例 2.2:JsonWriter類的使用方法public class DataReader { //通過JsonWriter類創建一個Json對象 public static void WriteJson () { System.Text.StringBuilder sb = new System.Text.StringBuilder(); JsonWriter writer = new JsonWriter (sb); writer.WriteArrayStart (); writer.Write (1); writer.Write (2); writer.Write (3); writer.WriteObjectStart (); writer.WritePropertyName ("color"); writer.Write ("blue"); writer.WriteObjectEnd (); writer.WriteArrayEnd (); Console.WriteLine (sb.ToString ()); //輸出:[1,2,3,{"color":"blue"}] } }