1.Gson的相关注解
@SerializedName---定义属性序列化后的名字
@Expose--区分实体中不想被序列化的属性
注意:使用
2.Gson gson=new GsonBuilder().create();
两个方法:toJson()和fromJson()
3.Obect:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
<span style="white-space:pre"> </span>response.setContentType("text/html");
<span style="white-space:pre"> </span>PrintWriter out = response.getWriter();
<span style="white-space:pre"> </span>Gson gson=new GsonBuilder().create();
<span style="white-space:pre"> </span>Mylist list=new Mylist();
<span style="white-space:pre"> </span>Thems t1=new Thems("1","厨房","www.chufang.cong");
<span style="white-space:pre"> </span>Thems t2=new Thems("2","卫浴","www.weiyu.com");
<span style="white-space:pre"> </span>Thems t3=new Thems("3","餐厅","www.canting.com");
<span style="white-space:pre"> </span>Thems t4=new Thems("4","楼梯","www.louti.com");
<span style="white-space:pre"> </span>Thems t5=new Thems("5","卧室","www.woshi.com");
<span style="white-space:pre"> </span>Thems t6=new Thems("6","书房","www.shufang.com");
<span style="white-space:pre"> </span>Thems t7=new Thems("7","客厅","www.keting.com");
<span style="white-space:pre"> </span>List<Thems> datas=new ArrayList<Thems>();
<span style="white-space:pre"> </span>datas.add(t1);
<span style="white-space:pre"> </span>datas.add(t2);
<span style="white-space:pre"> </span>datas.add(t3);
<span style="white-space:pre"> </span>datas.add(t4);
<span style="white-space:pre"> </span>datas.add(t5);
<span style="white-space:pre"> </span>datas.add(t6);
<span style="white-space:pre"> </span>datas.add(t7);
<span style="white-space:pre"> </span>list.setResponse(datas);
<span style="white-space:pre"> </span>String result=gson.toJson(list);
<span style="white-space:pre"> </span>out.println(result);
}
输出:{"response":[{"mOrders":"1","mTitle":"厨房","mUrl":"www.chufang.cong"},{"mOrders":"2","mTitle":"卫浴","mUrl":"www.weiyu.com"},{"mOrders":"3","mTitle":"餐厅","mUrl":"www.canting.com"},{"mOrders":"4","mTitle":"楼梯","mUrl":"www.louti.com"},{"mOrders":"5","mTitle":"卧室","mUrl":"www.woshi.com"},{"mOrders":"6","mTitle":"书房","mUrl":"www.shufang.com"},{"mOrders":"7","mTitle":"客厅","mUrl":"www.keting.com"}]}