拿PHP举例来说:
serialize 和 json 都是起到方便数据存储与传输的作用,比如存文件或写入数据库.
首先两者使用方法:
serialize:
$arr=array(); $arr['name']='张三'; $arr['age']='22'; $arr['sex']='男'; $arr['phone']='123456789'; $arr['address']='上海市浦东新区'; var_dump($arr);
输出:
array(5) { ["name"]=> string(6) "张三" ["age"]=> string(2) "22" ["sex"]=> string(3) "男" ["phone"]=> string(9) "123456789" ["address"]=> string(21) "上海市浦东新区" }
序列化:
$info=serialize($arr); var_dump($info);
输出:
string(140) "a:5:{s:4:"name";s:6:"张三";s:3:"age";s:2:"22";s:3:"sex";s:3:"男";s:5:"........
a代表array中元素数量,s代表字符串中有多少字符。
反序列化:
$zhangsan=unserialize($info); var_dump($zhangsan);
输出:
array(5) { ["name"]=> string(6) "张三" ["age"]=> string(2) "22" ["sex"]=> string(3) "男" ["phone"]=> string(9) "123456789" ["address"]=> string(21) "上海市浦东新区" }
json:
//将数组编码成json
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
json_encode($arr);
输出:
{"a":1,"b":2,"c":3,"d":4,"e":5}
//将json解码为数组,不写true就解码为对象
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json,));
var_dump(json_decode($json,true));
输出:
object(stdClass)#1 (5) { ["a"] => int(1) ["b"] => int(2) ["c"] => int(3) ["d"] => int(4) ["e"] => int(5) } array(5) { ["a"] => int(1) ["b"] => int(2) ["c"] => int(3) ["d"] => int(4) ["e"] => int(5) }
经测试,json_encode和json_decode比内置的serialize和unserialize函数要高效。所以建议用json.