List对象转成Gson字符串(两种方式)
[b](1)使用Gson gson=new Gson()类中的 gson.toJson(list);方法[/b]
案例 (ajax+json+jquery 省市县级联):
后台代码:
package com.zz.jquery;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.omg.IOP.Encoding;
import com.google.gson.Gson;
public class AjxServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//设置编码格式
response.setContentType("application/json;charset=utf-8");
//省
int province = Integer.parseInt(request.getParameter("province"));
//市
int city = Integer.parseInt(request.getParameter("city"));
System.out.println("province==>" + province);
System.out.println("city==>" + city);
//list对象
List list = new ArrayList();
if (province != 0) {
if (province == 1) {
TestJson tj = new TestJson();
//第一个对象
tj.setCityName("郴州市");
tj.setCityNo("10");
//第二个对象
TestJson tj2 = new TestJson();
tj2.setCityName("长沙市");
tj2.setCityNo("11");
//分别将对象加入到list中
list.add(tj);
list.add(tj2);
}
if (province == 2){
TestJson tj = new TestJson();
tj.setCityName("武汉市");
tj.setCityNo("20");
TestJson tj2 = new TestJson();
tj2.setCityName("十堰市");
tj2.setCityNo("21");
list.add(tj);
list.add(tj2);
}
}
if(city!=0){
if(city==10){
TestJson tj = new TestJson();
tj.setCountyNo("101");
tj.setCountyName("苏仙区");
TestJson tj2 = new TestJson();
tj2.setCountyNo("102");
tj2.setCountyName("北湖区");
list.add(tj);
list.add(tj2);
}
}
PrintWriter out = response.getWriter();
Gson gson = new Gson();
String reslut = gson.toJson(list);
System.out.println("reslut:" + reslut);
response.setHeader("pargma", "no-cache");
response.setHeader("cache-control", "no-cache");
out.println(reslut);
out.flush();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
前台jsp界面:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
无标题文档
web.xml文件添加以下代码
AjxServlet
com.zz.jquery.AjxServlet
AjxServlet
/AjxServlet
[b](2) 使用JSONArray json=JSONArray.fromobject(list);在调用json.toString()方法转换成字符串[/b]
只需要将上面后台代码的 Gson gson = new Gson();
String reslut = gson.toJson(list);
换成
JSONArray json=JSONArray.fromobject(list);
前提是list必须都为一个完整的对象
所需jar包:
json_java.jar
gson-1.6.jar
具体的项目源码请在附件中下载。