php array 转json及java 转换 json数据格式操作示例
程序员文章站
2023-11-24 21:45:58
本文实例讲述了php array 转json及java 转换 json数据格式操作。分享给大家供大家参考,具体如下:
php array 转json 数据
$arr = a...
本文实例讲述了php array 转json及java 转换 json数据格式操作。分享给大家供大家参考,具体如下:
php array 转json 数据
$arr = array( "demo1" => "my demo1", "demo2" => array( "demo2_demo1"=>"aaaaaaaa", "demo2_demo2"=>"bbbbbbbb", "demo2_demo3"=>array( "demo2_demo3_demo1"=>"ccccccc" ) ), "demo3" => 22 ); $json_str = json_encode($arr,true); $arr = json_decode($json_str,true); var_dump($json_str); var_dump($arr); //查看结果
运行结果:
string(137) "{"demo1":"my demo1","demo2":{"demo2_demo1":"aaaaaaaa","demo2_demo2":"bbbbbbbb","demo2_demo3":{"demo2_demo3_demo1":"ccccccc"}},"demo3":22}"
array(3) {
["demo1"]=>
string(8) "my demo1"
["demo2"]=>
array(3) {
["demo2_demo1"]=>
string(8) "aaaaaaaa"
["demo2_demo2"]=>
string(8) "bbbbbbbb"
["demo2_demo3"]=>
array(1) {
["demo2_demo3_demo1"]=>
string(7) "ccccccc"
}
}
["demo3"]=>
int(22)
}
java json数据格式转换依赖包
commons-beanutils-1.8.3.jar,
commons-collections-3.2.1.jar,
commons-lang-2.6.jar,
commons-logging-1.1.1.jar,
ezmorph-1.0.6.jar,
json-lib-2.4-jdk15.jar,
添加至构建路径。
package main; import net.sf.json.jsonobject; import net.sf.json.jsonarray; import java.util.map; import java.util.hashmap; import java.util.list; import java.util.arraylist; import main.demo1; public class index { public static void main(string[] args) { index4(); } /** * 简单的simple * */ public static void index1() { jsonobject json = new jsonobject(); json.element("name","谭勇"); json.element("age",22); system.out.println(json.tostring()); } /** * map 数据转json * */ public static void index2() { jsonobject json = new jsonobject(); map<string,string> map = new hashmap<string,string>(); map.put("name", "谭勇"); map.put("age", "22"); json.accumulateall(map); system.out.println(json.tostring()); } /** * list<map> 转json * */ public static void index3() { jsonarray arr = new jsonarray(); list<map<string,string>> list = new arraylist<map<string,string>>(); list.add(getmap("name","谭勇")); list.add(getmap("age","22")); arr.addall(list); system.out.println(arr.tostring()); } /** * 对象转json * */ public static void index4() { demo1 demo1 = new demo1(); demo1.setname("谭勇"); demo1.setage(22); jsonobject json = new jsonobject(); jsonarray arr = new jsonarray(); json.element("demo1",demo1); arr.add(demo1); //json.containskey(demo1); system.out.println(json.tostring()); system.out.println(arr.tostring()); } private static map<string,string> getmap(string key,string val) { map<string,string> map = new hashmap<string,string>(); map.put(key, val); return map; } }
demo1.java
package main; public class demo1 { private string name; private int age; public void setname(string name) { this.name = name; } public string getname() { return this.name; } public void setage(int age) { this.age = age; } public int getage() { return this.age; } }