【轉】在Unity中讀寫檔案資料:LitJSON快速教程

來源:互聯網
上載者:User

標籤:run   定義   boolean   資料   nsa   目的   app   strong   cat   

王選易,出處:http://www.cnblogs.com/neverdie/ 歡迎轉載,也請保留這段聲明。如果你喜歡這篇文章,請點【推薦】。謝謝!

 

 

介紹

JSON是一個簡單的,但功能強大的序列化資料格式。它定義了簡單的類型,如布爾,數(int和float)和字串,和幾個資料結構:list和dictionnary。可以在http://JSON.org瞭解關於JSON的更多資訊。

litjson是用C #編寫的,它的目的是要小,快速,易用。它使用了Mono架構。

安裝LitJSON

將LitJSON編譯好的dll檔案通過Import New Asset的方式匯入到項目中,再使用Using LitJSON即可使用JSONMapper類中的簡便方法。dll的在這裡.

將JSON轉化為Object並可逆向轉化

為了在.Net程式中使用JSON格式的資料。一個自然的方法是使用JSON文本產生一個特定的類的一個新執行個體;為了匹配類的格式,一般儲存的JSON字串是一個字典。

另一方面,為了將對象序列化為JSON字串,一個簡單的匯出操作,聽起來是個好主意。

為了這個目的,LitJSON包引入了JsonMapper類,它提供了兩個用於做到  JSON轉化為object 和 object轉化為JSON 的主要方法。這兩個方法是jsonmapper.toobject和jsonmapper.tojson。

將object轉化為字串之後,我們就可以將這個字串很方便地在檔案中讀取和寫入了。

一個簡單的JsonMapper的例子

在下面的例子中,ToObject方法有一個泛型參數,來指定返回的某種特定的資料類型:即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
使用非泛型的JsonMapper.ToObject

當不存在特定的JSON資料類時,它將返回一個JSONData執行個體。JSONData是一種通用型可以儲存任何資料類型支援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
Reader和Writer

一些人喜歡使用stream的方式處理JSON資料,對於他們, 我們提供的介面是jsonreader和jsonwriter。

JSONMapper實際上是建立在以上兩個類的基礎上的,所以你可以把這兩個類當成是litJSON的底層介面。

使用JsonReader
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
介紹安裝LitJSON將JSON轉化為Object並可逆向轉化一個簡單的JsonMapper的例子使用非泛型的JsonMapper.ToObjectReader和Writer使用JsonReader隱藏目錄

【轉】在Unity中讀寫檔案資料:LitJSON快速教程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.