【Unity3D插件】在Unity中读写文件数据:LitJSON快速教程

时间:2022-09-19 10:47:22

作者:王选易,出处:http://www.cnblogs.com/neverdie/ 欢迎转载,也请保留这段声明。如果你喜欢这篇文章,请点【推荐】。谢谢!

【Unity3D插件】在Unity中读写文件数据:LitJSON快速教程

介绍

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>。

using LitJson;
using System; public class Person
{
// C# 3.0 auto-implemented properties
public string Name { get; set; }
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 = ;
bill.Birthday = new DateTime(, , ); 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":,"Birthday":"04/26/1564 00:00:00"}
Thomas' age: 57

使用非泛型的JsonMapper.ToObject

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

using LitJson;
using System; 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"][]);
}
}

上面例子的输出:

Reading data from the following JSON string:
{
"album" : {
"name" : "The Dark Side of the Moon",
"artist" : "Pink Floyd",
"year" : ,
"tracks" : [
"Speak To Me",
"Breathe",
"On The Run"
]
}
} Album's name: The Dark Side of the Moon
Recorded by Pink Floyd in
First track: Speak To Me

Reader和Writer

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

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

使用JsonReader

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 ('-', )); // 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 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

【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&lpar;&rpar;&comma;读写文件数据的API&comma;以及复制文件操作

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

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

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

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

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

  9. PHP中读写文件

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

随机推荐

  1. VS2015突然报错————Encountered an unexpected error when attempting to resolve tag helper directive &&num;39&semi;&commat;addTagHelper&&num;39&semi; with value &&num;39&semi;Microsoft&period;AspNet&period;Mvc&period;Razor&period;TagHelpers&period;UrlResolutionTagHelper

    Encountered an unexpected error when attempting to resolve tag helper directive '@addTagHelper' with ...

  2. CSS3&colon;clip-path

    旧的clip 旧的css也提供了一个clip属性,但这个属性只能用于裁剪一个矩形,其本质是根据overflow:hidden隐藏掉了裁剪外的区域,使用: clip:rect(<top>,& ...

  3. oracle批量update 转

    需求: 将t2(t_statbuf)表中id和t1(T_Mt)表相同的记录更新进t1表. 1.错误的写法: update table_name t1 set (a,b,c)=( select a,b, ...

  4. java File详解

    一.简介 File类是“文件”和“目录名”的抽象表示形式.因此在java语言中,File类既可以表示文件也可以表示目录. 尽管java.io定义的大多数类是实行流式操作的,而File类则不是,它没有指 ...

  5. vs2015创建类时增加默认注释

    我是vs2015修改 C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\ItemTemplatesCache\CSharp ...

  6. CSS Core Technology

    1. Selector Different types of selectors: Selectors can be divided into the following categories: Si ...

  7. CS模式,客户端页面加载

    public MainForm() { //1.初始化视图 InitializeComponent(); //2.加载程序 this.Load += new System.EventHandler(t ...

  8. 局域网内客户端无法使用机器名连接SQLServer服务器

    在生产环境中有时会要求使用机器名连接SQLServer服务器,但有时捣好久都没法连上~ 针对这个问题做个简短记录,防止以后自己再遇到记不起原因,也方便一下其他同行! 废话不多说,作为工作多年的老家伙了 ...

  9. Flume 相关

    在CentOS 7上安装配置Flume https://mos.meituan.com/library/41/how-to-install-flume-on-centos7/ Flume NG 学习笔 ...

  10. 一个简单的获取RGB值方式

    操作系统内置了许多小工具,有时候这些小工具也挺有用的,省去了安装一些复杂的软件, 截图 通过键盘PrtSc获取到要取色的图片,然后用画图工具打开 查看 通过画图工具的取色工具,取到你需要的颜色,然后点 ...