作者:王选易,出处: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.  
  4. public class Person
  5. {
  6. // C# 3.0 auto-implemented properties
  7. public string Name { get; set; }
  8. public int Age { get; set; }
  9. public DateTime Birthday { get; set; }
  10. }
  11.  
  12. public class JsonSample
  13. {
  14. public static void Main()
  15. {
  16. PersonToJson();
  17. JsonToPerson();
  18. }
  19.  
  20. public static void PersonToJson()
  21. {
  22. Person bill = new Person();
  23.  
  24. bill.Name = "William Shakespeare";
  25. bill.Age = ;
  26. bill.Birthday = new DateTime(, , );
  27.  
  28. string json_bill = JsonMapper.ToJson(bill);
  29.  
  30. Console.WriteLine(json_bill);
  31. }
  32.  
  33. public static void JsonToPerson()
  34. {
  35. string json = @"
  36. {
  37. ""Name"" : ""Thomas More"",
  38. ""Age"" : 57,
  39. ""Birthday"" : ""02/07/1478 00:00:00""
  40. }";
  41.  
  42. Person thomas = JsonMapper.ToObject<Person>(json);
  43.  
  44. Console.WriteLine("Thomas' age: {0}", thomas.Age);
  45. }
  46. }

上文的输出:

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

上面例子的输出:

  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" : ,
  7. "tracks" : [
  8. "Speak To Me",
  9. "Breathe",
  10. "On The Run"
  11. ]
  12. }
  13. }
  14.  
  15. Album's name: The Dark Side of the Moon
  16. Recorded by Pink Floyd in
  17. First track: Speak To Me

Reader和Writer

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

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

使用JsonReader

  1. using LitJson;
  2. using System;
  3.  
  4. public class DataReader
  5. {
  6. public static void Main()
  7. {
  8. string sample = @"{
  9. ""name"" : ""Bill"",
  10. ""age"" : 32,
  11. ""awake"" : true,
  12. ""n"" : 1994.0226,
  13. ""note"" : [ ""life"", ""is"", ""but"", ""a"", ""dream"" ]
  14. }";
  15.  
  16. PrintJson(sample);
  17. }
  18.  
  19. public static void PrintJson(string json)
  20. {
  21. JsonReader reader = new JsonReader(json);
  22.  
  23. Console.WriteLine ("{0,14} {1,10} {2,16}", "Token", "Value", "Type");
  24. Console.WriteLine (new String ('-', ));
  25.  
  26. // The Read() method returns false when there's nothing else to read
  27. while (reader.Read()) {
  28. string type = reader.Value != null ?
  29. reader.Value.GetType().ToString() : "";
  30.  
  31. Console.WriteLine("{0,14} {1,10} {2,16}",
  32. reader.Token, reader.Value, type);
  33. }
  34. }
  35. }

输出如下:

  1. Token Value Type
  2. ------------------------------------------
  3. ObjectStart
  4. PropertyName name System.String
  5. String Bill System.String
  6. PropertyName age System.String
  7. Int System.Int32
  8. PropertyName awake System.String
  9. Boolean True System.Boolean
  10. PropertyName n System.String
  11. Double 1994.0226 System.Double
  12. PropertyName note System.String
  13. ArrayStart
  14. String life System.String
  15. String is System.String
  16. String but System.String
  17. String a System.String
  18. String dream System.String
  19. ArrayEnd
  20. ObjectEnd

【Unity3D插件】在Unity中读写文件数据:LitJSON快速教程的更多相关文章

  1. 【转】在Unity中读写文件数据:LitJSON快速教程

    作者:王选易,出处:http://www.cnblogs.com/neverdie/ 欢迎转载,也请保留这段声明.如果你喜欢这篇文章,请点[推荐].谢谢! 介绍 JSON是一个简单的,但功能强大的序列 ...

  2. 【转】 Linux内核中读写文件数据的方法--不错

    原文网址:http://blog.csdn.net/tommy_wxie/article/details/8193954 Linux内核中读写文件数据的方法  有时候需要在Linuxkernel--大 ...

  3. Unity中的文件

    Unity中的文件大致分为一下几类: 1.资源文件: 导入后,除非是修改,否则不会变化的文件.例如:fbx文件.贴图文件.音频文件.视频文件.动画文件等. 这些文件在导入到Unity的时候,都会进行转 ...

  4. Android简易实战教程--第十五话《在外部存储中读写文件》

    第七话里面介绍了在内部存储读写文件 点击打开链接. 这样有一个比较打的问题,假设系统内存不够用,杀本应用无法执行,或者本应用被用户卸载重新安装后.以前保存的用户名和密码都不会得到回显.所以,有必要注意 ...

  5. 在android中读写文件

    在android中读写文件 android中只有一个盘,正斜杠/代表根目录. 我们常见的SDK的位置为:/mnt/sdcard 两种最常见的数据存储方式: 一.内存 二.本地 1.手机内部存储 2.外 ...

  6. RandomAccessFile(),读写文件数据的API,以及复制文件操作

    package seday03;import java.io.File;import java.io.RandomAccessFile; import java.io.IOException; /** ...

  7. 应用 JD-Eclipse 插件实现 RFT 中 .class 文件的反向编译

    概述 反编译是一个将目标代码转换成源代码的过程.而目标代码是一种用语言表示的代码 , 这种语言能通过实机或虚拟机直接执行.文本所要介绍的 JD-Eclipse 是一款反编译的开源软件,它是应用于 Ec ...

  8. Android 怎样在linux kernel 中读写文件

    前言          欢迎大家我分享和推荐好用的代码段~~ 声明          欢迎转载,但请保留文章原始出处:          CSDN:http://www.csdn.net        ...

  9. PHP中读写文件

    在PHP中读写文件,可以用到一下内置函数: 1.fopen(创建文件和打开文件) 语法: 复制代码代码如下:fopen(filename,mode) filename,规定要打开的文件.mode,打开 ...

随机推荐

  1. PAT 10-0 说反话

    我写了两种实现方法,其中第二种是参考Yomman园友的(http://www.cnblogs.com/yomman/p/4271949.html).我的方法(方法一)是用一个数组存放输入的字符串,另一 ...

  2. 12-26 tableView的学习心得

    一:基础部分 UITableView的两种样式: 注意是只读的 1.UITableViewStytlePlain(不分组的) n 2.UITableViewStyleGrouped(分组的) 二:如何 ...

  3. LeetCode222 Count Complete Tree Nodes

    对于一般的二叉树,统计节点数目遍历一遍就可以了,但是这样时间复杂度O(n),一下就被卡住了. 这题首先要明白的是,我们只需要知道叶子节点的数目就能统计出总节点树. 想法1: 既然是完全二叉树,我肯定是 ...

  4. 解决:Ubuntu12.04下使用ping命令返回ping:icmp open socket: Operation not permitted的解决

    ping命令在运行中采用了ICMP协议,需要发送ICMP报文.但是只有root用户才能建立ICMP报文.而正常情况下,ping命令的权限应为-rwsr-xr-x,即带有suid的文件,一旦该权限被修改 ...

  5. Git ~ 管理修改 ~ Gitasd

    现在假设你一经常我了暂存区的概念 , 下面我们将要讨论的就是 , 为什么 Git 比其他的版本控制系统设计的优秀 , 因为 Git 跟踪管理的是修改而非文件 什么是修改  ? 修改就是 你在某个地方 ...

  6. Ubuntu安装Fcitx(小企鹅五笔输入法)

    安装配置如下: 1. 安装 fcitx sudo apt-get install fcitx 2. 配置默认输入法为 fcitx im-switch -s fcitx // 注意无须加 sudo 3. ...

  7. linux常用命令:1文件处理命令

    文件处理命令 1.命令格式 命令格式:命令 [-选项]  [参数] 例:ls  -la /etc 说明:1)个别命令使用不遵循此格式 2)档有多个选项时,可以写在一起 3)简化选项与完整选项 2.目录 ...

  8. 【LEETCODE OJ】Binary Tree Preorder Traversal

    Problem Link: http://oj.leetcode.com/problems/binary-tree-preorder-traversal/ Even iterative solutio ...

  9. Redis - hash类型操作

    hash 类型操作设置操作:hset:    hset key filed value        创建指定key的filed-value名值对 hsetnx:    hsetnx key file ...

  10. Washing Clothes_01背包

    Description Dearboy was so busy recently that now he has piles of clothes to wash. Luckily, he has a ...