这篇文章主要介绍了php array 转json及java 转换 json数据格式操作,结合实例形式分析了PHP针对array数组转json以及Java操作Map、List、对象与json格式转换的相关实现技巧,需要的朋友可以参考下
本文实例讲述了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.javapackage 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;
}
} 更多关于 JSONObject 提供的方法 JSONArray 提供的方法 自己探索。
希望本文所述对大家PHP程序设计有所帮助。
原文链接:https://blog.csdn.net/u014559227/article/details/73771373
|