json是一种与语言无关的数据交换的格式,作用:
使用ajax进行前后台数据交换
移动端与服务端的数据交换
1.Json的格式与解析
json有两种格式:
1)对象格式:{"key1":obj,"key2":obj,"key3":obj...}
2)数组/集合格式:[obj,obj,obj...]
例如:user对象 用json数据格式表示
{"username":"zhangsan","age":28,"password":"123","addr":"北京"}
List<Product> 用json数据格式表示
[{"pid":"10","pname":"小米4C"},{},{}]
var json={
"key1":"values",
"key2":{"firstname":"张","lastname":"三丰","age":100},
"key3":[
{"name":"小双","age":28,"addr":"扬州"},
{"name":"小双","age":18,"addr":"扬州"},
{"name":"小双","age":28,"addr":"柳州"}
]
}
alert(json.key2.lastname);
alert(json.key3[3].addr);
注意:对象格式和数组格式可以互相嵌套
注意:json的key是字符串 jaon的value是Object
json的解析:
json是js的原生内容,也就意味着js可以直接取出json对象中的数据
2.Json的转换插件
将java的对象或集合转成json形式字符串
json的转换插件是通过java的一些工具,直接将java对象或集合转换成json字符串。
常用的json转换工具有如下几种:
1)jsonlib
2)Gson:google 用的较多
3)fastjson:阿里巴巴 比较好
package com.itheima.web;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import com.itheima.domain.Product;
import com.itheima.service.ProductService;
import net.sf.json.JSONArray;
public class SsearchWordServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获得关键字
String word=request.getParameter("word");
//查询该关键字的所有商品
ProductService service=new ProductService();
List<Object> productList=null;
try {
productList=service.findproductWord(word);
} catch (SQLException e) {
e.printStackTrace();
}
//使用json的转换工具对象或者集合json格式的字符串
/*JSONArray fromObject = JSONArray.fromObject(productList);
String string = fromObject.toString();
System.out.println(string);*/
Gson gson=new Gson();
String json = gson.toJson(productList);
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write(json);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}