您的位置:首页 > 移动开发 > Unity3D

Unity下关于C#的文件读写三(Json格式读写-基于LitJson简单认识)

2016-11-08 15:29 941 查看
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来读写数据流(字符流);

第三,第四条详情请参见LitJson的快速使用向导:http://lbv.github.io/litjson/docs/quickstart.html

Note:

新添加一个坑:MissingMethodException: Method not found: ‘Default constructor not found…ctor() of bagItemJson’.

他们写的类和我的唯一不一样的地方就是构造函数,我是用构造函数赋值,初始化,但是他们是先实例化,然后在一个一个给每一个属性赋值,这个就是问题的关键了,因为我自己写了一个构造函数,把默认的构造函数给私有化了,这样的话在上面的转化为对象的时候,就找不到构造函数了,所以就转化不了实例了,这时候就会出现找不到该方法,实际上是找不到构造函数了

另外,值得一说的是,在转化为对象的方法里面,应该是先实例化出来一个对象,然后在给每个对象赋值,这时候的实例化是用默认构造函数实例化的,并不是用自己的构造函数实例化的,所以上面的错误只需要把默认构造函数给加上,写成Public就可以了

http://www.cnblogs.com/ZhiXing-Blogs/p/4914459.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  json unity