日期:2014-05-16  浏览次数:20356 次

List对象转成json字符串(两种方式)
List对象转成Gson字符串(两种方式)

(1)使用Gson gson=new Gson()类中的  gson.toJson(list);方法

案例 (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 + "/";
%>
<html>
<head>
<title>无标题文档</title>
  <script type="text/javascript" src="js/jquery-1.4.2.js"></script>
<script type="text/javascript">

function sub(){
     
      $.ajax({
type: "post",
url : 'AjxServlet',
data: { province:$('#province').val(), city:$('#city').val()},
success : function(result){
alert(result);
if(eval(result)) {

var html="<option v