Java 如何将json中的响应发送到servlet中的树结构
我是servlet新手,我成功地使用json简单包/jar文件向客户机发送了json格式;然后像进口一样进口-Java 如何将json中的响应发送到servlet中的树结构,java,json,servlet-3.0,simplejson,Java,Json,Servlet 3.0,Simplejson,我是servlet新手,我成功地使用json简单包/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.g
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中实现这一点 在尝试使嵌套的json和新代码成为- setContentType(“应用程序/json”) 您可以使用org.json.JSONObject的
toString(int-indentFactor)
方法。以下是链接:
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);