|
JSON格式是ajax里面比较常用的一种数据交换格式,比起xml来要方便,而且overhead很小。原来我做的web上的东西基本上数据传输很少用XML,都是用的JSON。关于JSON格式的好处和基础知识,不清楚的可以google一下,这里不详细写了。总体来说好处就是JSON比XML小、快、容易读,解析方便。
前两天写完那个javascript的贴子之后,就一直在琢磨,既然反正Unity3D用的是Javascript,而且支持eval,为啥不用JSON,还要用XML来做数据交换呢。google了一下,好像没有人提出过怎么在unity里使用json,国外就一个帖子还是想用但没解决的。
这个例子里做的事情很简单,主要做了两件事:
1 从服务器的php程序里读一个json数据,然后把内容显示出来。
2 把一个数据结构转换为JSON传给服务器。
所谓数据交换,一来一回,这个例子都做了。
首先第一个,写一个最简单的php程序生成json数据。
取名叫test.php
[mw_shl_code=php,true]<?php
$arr=array(
'username' => 'foo',
'password' => 'bar'
);
echo json_encode($arr);
?>[/mw_shl_code]
这个程序就是把$arr这个数组变成json格式的数据显示出来。php5以上都支持json_encode,如果是php4需要一个额外的支持程序,可以去json.org找。
第二个php程序是把从unity3d post过去的json数据转成数组使用。取名叫test1.php,也很简单。[mw_shl_code=php,true]<?php
$jsonstring=$_POST["jsonstring"];
$jsondata=json_decode(stripslashes($jsonstring),true);
echo $jsondata["password"];
?>[/mw_shl_code]在Unity里怎么用呢?也不难,下面是代码,随便取个什么名字都行。我取名叫jsontest.js。[mw_shl_code=javascript,true]var jsonURL="http://localhost/json/test.php";
var jsonURL1="http://localhost/json/test1.php";
function Start(){
//获取json数据的方法
var getwww : WWW = new WWW (jsonURL);
yield getwww;
var jsonObj1=eval(getwww.data);
print (jsonObj1["username"]);
//提交JSON数据的方法
var mydata=new Boo.Lang.Hash();
mydata["username"]="hello";
mydata["password"]="world";
//将数据转换为json字符串
var jsonstring=ToJSON(mydata);
var form = new WWWForm();
form.AddField("jsonstring", jsonstring);
var postwww: WWW = new WWW(jsonURL1, form);
yield postwww;
print(postwww.data);
}
/**
* 转换JSON
*/
static function ToJSON(obj){
if (obj==null) return "null";
var results=new Array();
for (var property in obj){
results.push("\""+property.Key+"\" : \""+property.Value+"\"");
}
return "{"+results.join(" , ")+"}";
}[/mw_shl_code]在Start()里,直接用eval把json转成boo.lang.hash格式,取出username,看console的话可以看到显示出了foo,也就是php里面$arr['username']。接着再提交一个username和password,叫hello和world,然后把php获取的反馈显示出来,会看到console里显示了world。
ToJSON()函数是我写的一个简单函数,就是把Boo.lang.hash数组转成json字符串,只能处理一维数组,如果谁有兴趣可以改一下让它支持多维数组。
这样一来,原来我习惯的json数据传输就可以用了,如果熟悉使用json格式的朋友会方便多了,原来习惯使用xml格式的朋友也推荐你研究下这种简单方便的格式,会提高一些程序效率。:victory: |
|