本文实例讲述了Zend Framework处理Json数据的方法。分享给大家供大家参考,具体如下:
JSON分隔符及意义
{} 用于实现对象的包含,对象都包含在大括号中 , 逗号用于分隔对象的不同属性,或者数组的元素 [] 用于存放数组,数组将存放在中括号中 : 用于表示键/值对的值,冒号前为键,冒号后为该键的值
JSON示例
{
 "addressbook":{
 "name":"Mary Lebow",
 "address":{
 "street":"5 Main Street",
 "city":"San Diego,CA",
 "zip":91912
 },
 "phoneNumbers":[
 "619 332-3452",
 "664 223-4667"
 ]
 }
}
使用JSON
语法:$json = Zend_Json::encode($phpNative); 说明:其中,参数$phpNative为PHP常见的数据类型,可以是数组、对象或者其他类型的数据。 函数返回值$json为符合JSON格式的一个字符串。
示例:
<?php
require_once("Zend/Json.php");
$temp = array(
 "a"=>0,
 "b"=>1,
 "c"=>array(
 "c-1"=>21,
 "c-2"=>22,
 "c-3"=>23,
 ),
 "d"=>3
);
$json = Zend_Json::encode($temp);
echo "临时数组内容为:";
echo "<pre>";
print_r($temp);
echo "</pre>";
echo "转换为JSON格式内容为:";
echo "<pre>";
print_r($json);
echo "</pre>";
结果为:
临时数组内容为:
Array
(
 [a] => 0
 [b] => 1
 [c] => Array
 (
 [c-1] => 21
 [c-2] => 22
 [c-3] => 23
 )
 [d] => 3
)
转换为JSON格式内容为:
{"a":0,"b":1,"c":{"c-1":21,"c-2":22,"c-3":23},"d":3}
将JSON解码为普通数据
语法:$phpNative = Zend_Json::decode($json);
示例:
<?php
require_once("Zend/Json.php");
$json = "{
 \"addressbook\":{
 \"name\":\"zhangsan\",
 \"address\":{
 \"street\":\"Chang an jie\",
 \"city\":\"BeiJing\",
 \"zip\":100001
 },
 \"phoneNumbers\":[
 \"010-12345678\",
 \"010-11111111\"
 ]
 }
}";
echo "解码前为:";
echo "<pre>";
print_r($json);
echo "</pre>";
$native = Zend_Json::decode($json);
echo "解码后为:";
echo "<pre>";
print_r($native);
echo "</pre>";
输出结果为:
解码前为:
{
 "addressbook":{
 "name":"zhangsan",
 "address":{
 "street":"Chang an jie",
 "city":"BeiJing",
 "zip":100001
 },
 "phoneNumbers":[
 "010-12345678",
 "010-11111111"
 ]
 }
}
解码后为:
Array
(
 [addressbook] => Array
 (
 [name] => zhangsan
 [address] => Array
 (
 [street] => Chang an jie
 [city] => BeiJing
 [zip] => 100001
 )
 [phoneNumbers] => Array
 (
 [0] => 010-12345678
 [1] => 010-11111111
 )
 )
)
说明:
在使用此方法对JSON内容进行解码时,可以将其解码为数组,也可以将其解码为对象。
具体有Zend_Json::decode()方法的第二个参数决定。
语法格式如下
phpNative=ZendJson::decode(phpNative=ZendJson::decode(json,Zend_Json::TYPE_OBJECT);
上个例子解码为对象后的结果为
解码后为:
stdClass Object
(
 [addressbook] => stdClass Object
 (
 [name] => zhangsan
 [address] => stdClass Object
 (
 [street] => Chang an jie
 [city] => BeiJing
 [zip] => 100001
 )
 [phoneNumbers] => Array
 (
 [0] => 010-12345678
 [1] => 010-11111111
 )
 )
)
小结:
Json的使用还是比较简单的,在接口应用上需要Json。它可以在不同的语言中共用。可以灵活的传递数据。作用与XML类似,但是比XML要节省带宽。
PS:针对json的各种常用操作,还可参考使用本站相关json在线工具:
在线JSON代码检验、检验、美化、格式化工具: http://tools.jb51.net/code/json
JSON在线格式化工具: http://tools.jb51.net/code/jsonformat
在线XML/JSON互相转换工具: http://tools.jb51.net/code/xmljson
json代码在线格式化/美化/压缩/编辑/转换工具: http://tools.jb51.net/code/jsoncodeformat
在线json压缩/转义工具: http://tools.jb51.net/code/json_yasuo_trans
C语言风格/HTML/CSS/json代码格式化美化工具: http://tools.jb51.net/code/ccode_html_css_json