Unity下關於C#的檔案讀寫三(Json格式讀寫-基於LitJson簡單認識)
Unity使用LitJson需要下載litjson.dll檔案,放置在工程中的Plugins資料夾下(如果沒有自己新建);
使用using LitJson; 名稱空間
一:
類轉換為Json格式文字:
//首先隨意建立一個類
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public DateTime Birthday { get; set; }
}
//之後便可以使用JsonMapper.ToJson(類物件名)將其轉換為Json格式字串
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);
}
//同樣,我們建立一個Json格式的字串,使用JsonMapper.ToObject<Person>(json格式字串)將其轉換為Person類
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);
}
二:
使用non-generic variant(非泛型變數) : JsonMapper.ToObject;
如果從Json字串轉換至自定義的類不可用,便可使用JsonMapper.ToObject,將會返回一個JsonData例項,
這是一個通用型類,可以接受所有被Json支援的data型別,包括List和Dictionary;
string json =
@"{
""album"" :
{
""name"" : ""The Dark Side of the Moon"",
""artist"" : ""Pink Floyd"",
""year"" : 1973,
""tracks"" : [ ""Speak To Me"",""Breathe"",""On The Run""]
}
}";
//在呼叫此方法
public static void LoadAlbumData(string json_text)
{
JsonData data = JsonMapper.ToObject(json_text);
// 輸出"album"關鍵字下的"name"屬性內容
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]);
}
三:
JsonReader reader;reader.Read() 可以遍歷獲取每個屬性值,輸出他們
屬性名( reader.Token);屬性值(reader.Value);以及值型別( reader.Value.GetType().ToString() ) 等;
四:
以及通過JsonReader和JsonWriter來讀寫資料流(字元流);
Note:
新新增一個坑:MissingMethodException: Method not found: ‘Default constructor not found…ctor() of bagItemJson’.
他們寫的類和我的唯一不一樣的地方就是建構函式,我是用建構函式賦值,初始化,但是他們是先例項化,然後在一個一個給每一個屬性賦值,這個就是問題的關鍵了,因為我自己寫了一個建構函式,把預設的建構函式給私有化了,這樣的話在上面的轉化為物件的時候,就找不到構造函數了,所以就轉化不了例項了,這時候就會出現找不到該方法,實際上是找不到構造函數了
另外,值得一說的是,在轉化為物件的方法裡面,應該是先例項化出來一個物件,然後在給每個物件賦值,這時候的例項化是用預設建構函式例項化的,並不是用自己的建構函式例項化的,所以上面的錯誤只需要把預設建構函式給加上,寫成Public就可以了
http://www.cnblogs.com/ZhiXing-Blogs/p/4914459.html