分享

Unity,LitJSON处理JSON格式数据

 许多润泽 2013-01-17
各种粘贴,原作者见谅,开源有码万岁

LitJSON是一个.NET平台下处理JSON格式数据的类库,小巧、快速。它的源代码使用C#编写,可以通过任何.Net平台上的语言进行调用,目前最新版本为LitJSON 0.5.0。
LitJson.dll下载:
下载地址一: LitJSON.dll (点击直接下载)
下载地址二: http://litjson.
下载地址三: http://code.google.com/p/litjsonmd/


怎样在Unity3D中使用Json

Unity3D中的javascript有些特异,和普通的javascript差异很大,其中eval就没法在iOS下使用(其实我在桌面版本也没有使用成功过)使得Json解析这种在javascript中非常原生态的事情变得不那么直接了。

直接使用eval后Unity3D给的错误信息很高端,我是没有看懂,应该是没有找到eval这个通用的函数:

Mono: AssemblyAssets/Scripts/Example/JTianLingExample.js(1,1): BCE0172: `UnityScript.Scripting.IEvaluationDomainProvider’ interface member implementation must be public or explicit.

在网上找到了litjson库,通过这个支持.Net的库来曲线救国,折腾了一下,基本搞定。看网上讲litjson的资料很少,并且以C#居多,我这里就记录一下。

LitJson配置步骤

1.讲litjson的源代码中所有.cs文件放到Unity3d的assets中的plugins目录下,当然,在plugins下再建一个目录最好。Unity3D文档描述中plugins目录中的脚本会先运行,这样保证在我们写其他脚本的时候,litjson已经加载并运行好了。不然的话,等着报这种错误吧:
Mono: Image addref Mono.Cecil 0×1757740 -> /Applications/Unity/Unity.app/Contents/FramAssets/Scripts/Example/JTianLingExample.js(5,20): BCE0018: The name ‘LitJson.JsonData’ does not denote a valid type (‘not found’).

2.讲源代码放到plugins目录下后,会发现在Unity3d的editor中运行已经正常了,但是monodevelop中写javascript来调用litjson还是会报错误,也就是说monodevelop还是没有先运行litjson。因为C#的代码和javascript的代码在Unity3d生成的 项目中实际在几个不同的Project中,我们需要再配置一下:
在MonoDevelop中的Project->Edit Reference->Projects中,选择一下引用项(就像VS中添加项目依赖一样)
这里我们也会看到,放在plugins目录下的会放在Assembly-CSharp-firstpass中,而一般的脚本会放在Assembly-CSharp目录中。选上Assembly-CSharp-firstpass。

此时再在MonoDevelop中编译代码,顺利编译成功。

LitJson使用方式

1.解析json

var s : String = '{"name":"jtianling", "phone" : ["135xxx", "186xxx"]}';
var json : LitJson.JsonData = LitJson.JsonMapper.ToObject(s);
print(json['name']);

if (json['phone'].IsArray) {
  for (var json_data : LitJson.JsonData in json['phone']) {
    print(json_data);
  }
}

输出名字和两个电话号码,如上所示,其实直接把JsonData当一个Map使用就好了,同时,还有一堆用于判断类型的IsXXX变量。比如,上例中,判断是否是数组的变量就是IsArray。

2.生成json字符串:

var data : Hashtable = Hashtable();
data['name'] = 'aaa';
var array : Array = Array();
array.Add('haha');
array.Add('haha2');
data['good'] = array;
var data_string : String = LitJson.JsonMapper.ToJson(data);
print(data_string);

输出:{“good”:["haha","haha2"],”name”:”aaa”}

也就是把使用map的过程反过来而已,不详细描述了。

另外,我们读取配置文件的时候常常是从文件中读取,我发现用Unity3D读取文件也值得单独写写,这个下次再讲。

  JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。它基于JavaScriptStandard ECMA-262 3rd Edition - December 1999)的一个子集。 JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C, C++, C#, Java, JavaScript, Perl, Python等)。这些特性使JSON成为理想的数据交换语言。易于人阅读和编写,同时也易于机器解析和生成。

              如果曾经使用过Json,就会清楚Json可以分为两个部分:

1.         Json ObjectA collection of name/value pairs

2.         JSON Array An ordered list of values

解析JSON的开源包非常多,在各种场合使用非常广泛,尤其长于网络传输。

本文介绍使用LitJson,并用C#语言来介绍使用JSON,可以在C#应用程序,web程序,还有Unity3d C#脚本中使用。

 

第一步:先去下载LitJson并导入当前的项目。

第二步:litJson的几个实例方式

              1.使用JsonData来处理生成json:{"name":"peiandsky","age":28,"sex":"male"}

      

复制代码
  JsonData data = new JsonData();

        data["name"] = "peiandsky";

        data["age"] = 28;

        data["sex"] ="male";

        string  json1= data.ToJson();
复制代码

 

      2.对象中嵌套对象:{"name":"peiandsky","info":{"sex":"male","age":28}}

       

复制代码
 JsonData data2 = new JsonData();

        data2["name"] = "peiandsky";

        data2["info"] = new JsonData();

        data2["info"]["sex"] = "male";

        data2["info"]["age"] = 28;

string  json2 = data2.ToJson();
复制代码

 

 

 

3.         将上述两种方式的Json解析到JsonData

  JsonData jsonData2 = JsonMapper.ToObject(json2);

  Debug.Log(jsonData2["name"] + "    " + data2["info"]["sex"]);

 

 

 

4.         使用JsonMapper来处理Json

复制代码
Player player = new Player();

        player.name = "peiandsky";

        player.age = 23;

        player.sex = "male";

        string json=JsonMapper.ToJson(player);
复制代码

 

 

5.         解析4中的json

Player player2 = JsonMapper.ToObject<Player>(json);

 

 

 

6.         使用最原始的方式生成Json

将数组转换成json:["one","two","three","four"]

      

复制代码
  JsonWriter writer = new JsonWriter();

        writer.WriteArrayStart();

        writer.Write("one");

        writer.Write("two");

        writer.Write("three");

        writer.Write("four");

        writer.WriteArrayEnd();
复制代码

 

 

 

 

将复合对象转换成json字符串:{"book":{"title":"android game!","author":"pei","bookdetail":{"pages":429,"about":null}}}

 

        

复制代码
JsonWriter writer2 = new JsonWriter();

 

        writer2.WriteObjectStart();

        writer2.WritePropertyName("book");

 

        writer2.WriteObjectStart();

        writer2.WritePropertyName("title");

        writer2.Write("android game!");

        writer2.WritePropertyName("author");

        writer2.Write("pei");

        writer2.WritePropertyName("bookdetail");

 

        writer2.WriteObjectStart();

        writer2.WritePropertyName("pages");

        writer2.Write(429);

        writer2.WritePropertyName("about");

        writer2.Write(null);

        writer2.WriteObjectEnd();

 

        writer2.WriteObjectEnd();

 

        writer2.WriteObjectEnd();

        Debug.Log(writer2.ToString());
复制代码

 

 

 

 

 

这种方式非常不方便,不建议使用。

 

在使用LitJson中,建议使用JsonDataJsonMapper来处理Json的编码和解析。

复制代码
Person[] p_array = { p,p,p};

        string json_array=JsonMapper.ToJson(p_array);

        Debug.Log(json_array);

 

        JsonData pa = JsonMapper.ToObject(json_array);

 

        Debug.Log(pa.IsArray+"     "+pa.Count);

 

        for (int i = 0; i < pa.Count;i++ )

        {

            Debug.Log(pa[i]["name"]+"-"+pa[i]["age"]+"-"+pa[i]["score"]+"-"+pa[i]["birth"]);

            int age = int.Parse(pa[i]["age"].ToString());

            Debug.Log(age);

        }

 
复制代码

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约