Search code examples
javajsonservlet-3.0simplejson

how to send response in json to a tree structure in servlet


i am new to servlet and i succeeded to send a json format to the client using json-simple package/jar file; and import it like-

import org.json.simple.JSONObject;  

and to get response in json i have following code-

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);

and its format is like:

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

and works fine, but i need json format like-

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

and dont have any idea how to achieve this in servlet;


Solution

  • It works fine while try to make nested json and new code become- response.setContentType("application/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);