将java的对象或集合转成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;
le.gson.Gson;
import com.itheima.domain.Product;
import com.itheima.service.ProductService;
import net.sf.json.JSONArray;
zilla.javascript.internal.json.JsonParser;
public class SearchWordServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//获得关键字
String word = Parameter("word");
//查询该关键字的所有商品
ProductService service = new ProductService();
List<Object> productList = null;
json转换对象try {
productList = service.findProductByWord(word);
} catch (SQLException e) {
e.printStackTrace();
}
//["xiaomi","huawei",""...]
//使⽤json的转换⼯具将对象或集合转成json格式的字符串    jsonlib⼯具
/*JSONArray fromObject = JSONArray.fromObject(productList);
String string = String();
System.out.println(string);*/
//Gson⼯具
Gson gson = new Gson();
String json = Json(productList);
System.out.println(json);
response.setContentType("text/html;charset=UTF-8");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。