如何将json中的响应发送到servlet中的树结构

时间:2015-10-23 00:06:02

标签: java json servlet-3.0 simplejson

我是servlet的新手,我成功地使用json-simple package / jar文件将json格式发送到客户端;并导入它 - 如 -

import org.json.simple.JSONObject;  

并在json中获得响应我有以下代码 -

response.setContentType("application/json");
JSONObject obj = new JSONObject();
obj.put("name", "veshraj joshi");
obj.put("id",request.getParameter("id"));
obj.put("num", new Integer(100));
obj.put("balance", new Double(1000.21));
out.println(obj);

,其格式如下:

{"name":"veshraj joshi","id":"","num":"100","balance":"1000.21"}

并且工作正常, 但我需要json格式,如 -

{ status:"ok",
  message:"record has been added successfully",
  data:{
        name:"veshraj joshi",
        email:"email@gmail.com",
        address:"kathmandu, Nepal"
     }
 }

并且不知道如何在servlet中实现这一点;

1 个答案:

答案 0 :(得分:1)

在尝试使嵌套的json和新代码成为 - 时,它工作正常 response.setContentType( “应用程序/ JSON”);

JSONObject obj = new JSONObject();
JSONObject obj1 = new JSONObject();
obj1.put("email",'email@gmail.com');
obj1.put("name", "veshraj joshi");
obj1.put("id",request.getParameter("id"));
obj1.put("num", new Integer(100));
obj1.put("balance", new Double(1000.21));
obj.put("status","ok");
obj.put("message","record has been added successfully");
obj.put("data",obj1);
out.println(obj);