Unity 读写Json数据:LitJSON快速教程

出处: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>。

  1. using LitJson;
  2. using System;
  3. public class Person
  4. {
  5. // C# 3.0 auto-implemented properties
  6. public string Name { get; set; }
  7. public int Age { get; set; }
  8. public DateTime Birthday { get; set; }
  9. }
  10. public class JsonSample
  11. {
  12. public static void Main()
  13. {
  14. PersonToJson();
  15. JsonToPerson();
  16. }
  17. public static void PersonToJson()
  18. {
  19. Person bill = new Person();
  20. bill.Name = "William Shakespeare";
  21. bill.Age = 51;
  22. bill.Birthday = new DateTime( 1564, 4, 26);
  23. string json_bill = JsonMapper.ToJson(bill);
  24. Console.WriteLine(json_bill);
  25. }
  26. public static void JsonToPerson()
  27. {
  28. string json = @"
  29. {
  30. ""Name"" : ""Thomas More"",
  31. ""Age"" : 57,
  32. ""Birthday"" : ""02/07/1478 00:00:00""
  33. }";
  34. Person thomas = JsonMapper.ToObject<Person>(json);
  35. Console.WriteLine( "Thomas' age: {0}", thomas.Age);
  36. }
  37. }

上文的输出:

  1. { "Name": "William Shakespeare", "Age": 51, "Birthday": "04/26/1564 00:00:00"}
  2. Thomas ' age: 57

使用非泛型的JsonMapper.ToObject

当不存在特定的JSON数据类时,它将返回一个JSONData实例。JSONData是一种通用型可以保存任何数据类型支持JSON,包括list和dictionary。

  1. using LitJson;
  2. using System;
  3. public class JsonSample
  4. {
  5. public static void Main()
  6. {
  7. string json = @"
  8. {
  9. ""album"" : {
  10. ""name"" : ""The Dark Side of the Moon"",
  11. ""artist"" : ""Pink Floyd"",
  12. ""year"" : 1973,
  13. ""tracks"" : [
  14. ""Speak To Me"",
  15. ""Breathe"",
  16. ""On The Run""
  17. ]
  18. }
  19. }
  20. ";
  21. LoadAlbumData(json);
  22. }
  23. public static void LoadAlbumData(string json_text)
  24. {
  25. Console.WriteLine( "Reading data from the following JSON string: {0}",
  26. json_text);
  27. JsonData data = JsonMapper.ToObject(json_text);
  28. // Dictionaries are accessed like a hash-table
  29. Console.WriteLine( "Album's name: {0}", data[ "album"][ "name"]);
  30. // Scalar elements stored in a JsonData instance can be cast to
  31. // their natural types
  32. string artist = ( string) data[ "album"][ "artist"];
  33. int year = ( int) data[ "album"][ "year"];
  34. Console.WriteLine( "Recorded by {0} in {1}", artist, year);
  35. // Arrays are accessed like regular lists as well
  36. Console.WriteLine( "First track: {0}", data[ "album"][ "tracks"][ 0]);
  37. }
  38. }

上面例子的输出:

  1. Reading data from the following JSON string:
  2. {
  3. "album" : {
  4. "name" : "The Dark Side of the Moon",
  5. "artist" : "Pink Floyd",
  6. "year" : 1973,
  7. "tracks" : [
  8. "Speak To Me",
  9. "Breathe",
  10. "On The Run"
  11. ]
  12. }
  13. }
  14. Album 's name: The Dark Side of the Moon
  15. Recorded by Pink Floyd in 1973
  16. First track: Speak To Me

Reader和Writer

一些人喜欢使用stream的方式处理JSON数据,对于他们, 我们提供的接口是jsonreader和jsonwriter。

JSONMapper实际上是建立在以上两个类的基础上的,所以你可以把这两个类当成是litJSON的底层接口。

使用JsonReader

  1. using LitJson;
  2. using System;
  3. public class DataReader
  4. {
  5. public static void Main()
  6. {
  7. string sample = @"{
  8. ""name"" : ""Bill"",
  9. ""age"" : 32,
  10. ""awake"" : true,
  11. ""n"" : 1994.0226,
  12. ""note"" : [ ""life"", ""is"", ""but"", ""a"", ""dream"" ]
  13. }";
  14. PrintJson(sample);
  15. }
  16. public static void PrintJson(string json)
  17. {
  18. JsonReader reader = new JsonReader(json);
  19. Console.WriteLine ( "{0,14} {1,10} {2,16}", "Token", "Value", "Type");
  20. Console.WriteLine ( new String ( '-', 42));
  21. // The Read() method returns false when there's nothing else to read
  22. while (reader.Read()) {
  23. string type = reader.Value != null ?
  24. reader.Value.GetType().ToString() : "";
  25. Console.WriteLine( "{0,14} {1,10} {2,16}",
  26. reader.Token, reader.Value, type);
  27. }
  28. }
  29. }
输出如下:
 
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
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值