请关注“知了堂学习社区”,地址:http://www.zhiliaotang.com/portal.php
1.json字符串
var str1 = '{"name":"xxx","sex":"man"}';
2.json对象
var str2 = '{"name":"xxx","sex":"man"}';
3.JavaBean转json
<button id="str02">javaBean</button>
<p id="info"></p>
$("str02").onclick = function() {
loadTextData("ajax_xml.do?method=javaBeanToJson", "GET", true, function() {
if(xmlHttpReq.readyState == 4 && xmlHttpReq.status == 200) {
var res = xmlHttpReq.responseText; // 获得是一个JSON字符串
// JSON字符串转JSON对象
var obj = JSON.parse(res);
// 将数据渲染到页面上
$("info").innerText = "id : " + obj.id + " name : " + obj.name + " age : " + obj.age;
}
}, null);
}
private void javaBeanToJson(HttpServletRequest request,
HttpServletResponse response) throws IOException {
// TODO Auto-generated method stub
PrintWriter out = response.getWriter();
AjaxBean ajaxBean = new AjaxBean(1001, "zhangsan", 23);
Gson gson = new Gson();
String json = gson.toJson(ajaxBean); // 将JavaBean对象转成Json
out.println(json);
out.flush();
out.close();
}
4.list转json
<button id="str03">List</button>
$("str03").onclick = function() {
loadTextData("ajax_xml.do?method=listToJson", "GET", true, function() {
if(xmlHttpReq.readyState == 4 && xmlHttpReq.status == 200) {
var res = xmlHttpReq.responseText; // 获得是一个JSON字符串
// JSON字符串转JSON对象
var obj = JSON.parse(res);
var info = "";
for(i = 0; i < obj.length; i++) {
info += "id : " + obj[i].id + " name : " + obj[i].name + " age : " + obj[i].age + "\n\n";
}
$("info").innerText = info;
}
}, null);
}
private void listToJson(HttpServletRequest request,
HttpServletResponse response) throws IOException {
// TODO Auto-generated method stub
response.setContentType("text/plain; charset=utf-8");
PrintWriter out = response.getWriter();
List<AjaxBean> list = new ArrayList<>();
for(int i = 0; i < 3; i++) {
AjaxBean ajaxBean = new AjaxBean(i, "zhangsan", 23);
list.add(ajaxBean);
}
Gson gson = new Gson();
String json = gson.toJson(list);
out.println(json);
out.flush();
out.close();
}