日期:2014-05-18  浏览次数:20770 次

请教一个gson转换的问题
String hql="from VdDicMedicine where c17='1'";
List<VdDicMedicine> list=dao.getList(hql);

Gson gson = new Gson();
List<medicineList> medList = new ArrayList<medicineList>();  

for(int i=0;i<list.size();i++)
{
medicineList medBean = new medicineList();  
medBean.setName(list.get(i).getC02());
medBean.setPinyin(list.get(i).getC03());
medBean.setPrice(list.get(i).getC19()+"");
medBean.setStock(list.get(i).getC20()+"");
medList.add(medBean);
}  
java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<List<medicineList>>() {}.getType(); 

Map totalMap = new HashMap();

System.out.println(gson.toJson(medList,type));

totalMap.put("total",239);
totalMap.put("rows", gson.toJson(medList,type));

System.out.println(gson.toJson(totalMap));
response.setCharacterEncoding("gbk");
response.getWriter().print(gson.toJson(totalMap));初用gson发现挺方便的,想获取一个json形式的数据,但是如上这么写的话,输入出来是这样的: 

{"total":239,"rows":"[{\"name\":\"青霉素\",\"pinyin\":\"QMS\",\"price\":\"4.19\"  
,\"stock\":\"20.0\"},{\"name\":\"苯唑西林\",\"pinyin\":\"BZXL\",\"price\":\"16.1  
9\",\"stock\":\"45.0\"},{\"name\":\"阿莫西林\",\"pinyin\":\"AMXL\",\"price\":\"2  
65.33\",\"stock\":\"0.0\"},{\"name\":\"氨苄西林\",\"pinyin\":\"ABXL\",\"price\":  
\"265.33\",\"stock\":\"0.0\"}]"}  
{"total":239,"rows":"[{\"name\":\"青霉素\",\"pinyin\":\"QMS\",\"price\":\"4.19\"
,\"stock\":\"20.0\"},{\"name\":\"苯唑西林\",\"pinyin\":\"BZXL\",\"price\":\"16.1
9\",\"stock\":\"45.0\"},{\"name\":\"阿莫西林\",\"pinyin\":\"AMXL\",\"price\":\"2
65.33\",\"stock\":\"0.0\"},{\"name\":\"氨苄西林\",\"pinyin\":\"ABXL\",\"price\":
\"265.33\",\"stock\":\"0.0\"}]"}
多了很多的"\",而且"rows":后面的内容也不需要被双引号引起来,似乎是嵌套上出了问题,应该改哪里呢? 



------解决方案--------------------
Java code
package ExamProject.console.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ExamProject.console.jdbc.JDBCConnection;

import net.sf.json.JSONArray;

public class SelectAllServer extends HttpServlet {

    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        System.out.println("SelectAllServer");