天天看點

[C#技術] .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();

與以下這幾個.Net平台上的開源JSON庫相比,LitJSON的性能遙遙領先:

下面介紹LitJSON中常用的方法:

以下示例需要先添加引用LitJson.dll,再導入命名空間 using LitJson;

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

例 1.2:使用 JsonMapper 類将Json字元串轉換為C#認識的JsonData,再通過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);

}

//輸出結果:

//      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類的使用方法 

    //通過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"}]

更詳細的可參考 http://litjson.sourceforge.net/doc/manual.html (英文)

繼續閱讀