一.json常用转换方法
1.list
List list = new ArrayList();
list.add("first");
list.add("second");
JSONArray jsonArray2 = JSONArray.fromObject(list);
2.map
Map map = new HashMap();
map.put("name", "json");
map.put("bool", Boolean.TRUE);
map.put("int", new Integer(1));
map.put("arr", new String[] { "a", "b" });
map.put("func", "function(i){ return this.arr[i]; }");
JSONObject json = JSONObject.fromObject(map);
3.bean
JSONObject jsonObject = JSONObject.fromObject(new JsonBean());
4.数组
boolean[] boolArray = new boolean[] { true, false, true };
JSONArray jsonArray1 = JSONArray.fromObject(boolArray);
5.一般数据
JSONArray jsonArray3 = JSONArray.fromObject("['json','is','easy']" );
6.beans
List list = new ArrayList();
JsonBean2 jb1 = new JsonBean2();
jb1.setCol(1);
jb1.setRow(1);
jb1.setValue("xx");
JsonBean2 jb2 = new JsonBean2();
jb2.setCol(2);
jb2.setRow(2);
jb2.setValue("");
list.add(jb1);
list.add(jb2);
JSONArray ja = JSONArray.fromObject(list);
二.HTML页面将String转换成json
eval()
function testFunction() {
var jsonStr = '${str}';
var dataObj = eval("(" + jsonStr + ")");//转换为json对象
$.each(dataObj.info, function(idx, item) {
alert("name:" + item.uuid + " , vaddress:" + item.vaddress);
});
}
三.后台向前台传json
1.使用转义符 \
2.交给前台来处理 eval()
3.使用json工具类
后台代码:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.返回标准的json字符串(双引号要用转义符)
//String s = "[{\"id\":1,\"text\":\"Root node\",\"children\":[{\"id\":2,\"text\":\"Child node 1\",\"children\":true},{\"id\":3,\"text\":\"Child node 2\"}]}]";
//2.前台使用eval()函数将string装换成json格式
//String s = "[{id:1,text:'Root node',children:[{id:2,text:'Child node 1',children:true},{id:3,text:'Child node 2'}]}]";
//3.使用json工具类
JSONArray s = getJson();
response.setContentType("json");
response.getWriter().print(s);
}
private JSONArray getJson() {
JSONObject jo1 = new JSONObject();
JSONObject jo2 = new JSONObject();
jo1.put("id", 2);
jo1.put("text", "Child node 1");
jo2.put("id", 3);
jo2.put("text", "Child node 2");
JSONArray jsonArray = new JSONArray();
jsonArray.add(jo1);
jsonArray.add(jo2);
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", 1);
jsonObject.put("text", "Root node");
jsonObject.put("children", jsonArray);
JSONArray json = new JSONArray();
json.add(jsonObject);
return json;
}
前台代码:
<div id="jstree"></div>
<script>
$(function() {
$.ajax({
url : "IndexServlet",
datatype : "json",
success : function(o) {
create(o);
}
});
});
function create(data) {
//data = eval("(" + data + ")");
$('#jstree').jstree({
"core" : {
"data" : data
},
});
}
/* $(function() {
$('#jstree').jstree({
'core' : {
'data' : {
"url" : "IndexServlet",
"data" : function(node) {
return {
"id" : node.id
};
},
"dataFilter" : function(o) {
o = eval("(" + o + ")");
console.info(o);
return o;
}
}
}
});
}); */
</script>