Unity读写Json数据:LitJSON快速教程
litjson是⽤C #编写的,它的⽬的是要⼩,快速,易⽤。它使⽤了Mono框架。
将LitJSON编译好的dll⽂件通过Import New Asset的⽅式导⼊到项⽬中,再使⽤Using LitJSON即可使⽤JSONMapper类中的简便⽅法。dll 的下载地址在.
为了在.Net程序中使⽤JSON格式的数据。⼀个⾃然的⽅法是使⽤JSON⽂本⽣成⼀个特定的类的⼀个新实例;为了匹配类的格式,⼀般存储的JSON字符串是⼀个字典。
另⼀⽅⾯,为了将对象序列化为JSON字符串,⼀个简单的导出操作,听起来是个好主意。
为了这个⽬的,LitJSON包引⼊了JsonMapper类,它提供了两个⽤于做到  JSON转化为object 和 object转化为JSON 的主要⽅法。这两个⽅法是bject和json。
将object转化为字符串之后,我们就可以将这个字符串很⽅便地在⽂件中读取和写⼊了。
在下⾯的例⼦中,ToObject⽅法有⼀个泛型参数,来指定返回的某种特定的数据类型:即JsonMapper.ToObject<T>。
public class Person
{
// C# 3.0 auto-implemented properties
public string  Name    { get; set; }
writeline教程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
当不存在特定的JSON数据类时,它将返回⼀个JSONData实例。JSONData是⼀种通⽤型可以保存任何数据类型⽀持JSON,包括list和dictionary。
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 Moon
Recorded by Pink Floyd in 1973
First track: Speak To Me
⼀些⼈喜欢使⽤stream的⽅式处理JSON数据,对于他们,我们提供的接⼝是jsonreader和jsonwriter。JSONMapper实际上是建⽴在以上两个类的基础上的,所以你可以把这两个类当成是litJSON的底层接⼝。
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

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。