將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;
import sun.org.mozilla.javascript.internal.json.JsonParser;
public class SearchWordServlet 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.findProductByWord(word);
} catch (SQLException e) {
e.printStackTrace();
}
//["xiaomi","huawei",""...]
//使用json的轉換工具將對象或集合轉成json格式的字符串 jsonlib工具
/*JSONArray fromObject = JSONArray.fromObject(productList);
String string = fromObject.toString();
System.out.println(string);*/
//Gson工具
Gson gson = new Gson();
String json = gson.toJson(productList);
System.out.println(json);
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write(json);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
