[C#技術] .NET平台開源JSON庫LitJSON的使用方法

來源:互聯網
上載者:User

一個簡單樣本:

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

:下載

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

例 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);
        }
    }
}
      
//輸出結果:

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

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.