0

I want to read this json in a servlet

{
    "text" : "ABC",
    "msg" : "9551667858",
    "all":[
        {"name":"one"},
        {"name":"two"}
        ],
    "obj":{
        "firstname":"John",
        "lastname":"Doe"
    }
}

Now i want to get this values to separately to string,jsonarray and json object

this is how i do that

PrintWriter out = response.getWriter();
        try {
            String newObj = request.getParameter("text");;
            JSONObject jObj    = new JSONObject(request.getParameter("obj"));
            JSONArray jArray=new JSONArray(request.getParameter("all"));

out.print(newObj);

        } catch (Exception e) {
            e.printStackTrace();
            out.write(e.toString());
        }
        response.setContentType("application/json");
Lakshan
  • 208
  • 1
  • 4
  • 17

3 Answers3

2

your code is partially correct.String newObj = request.getParameter("jsondata"); is correct. Then you have to create the jObj from newObj string.

String jsonString = <your json String>
JSONObject jsonObj = new JSONObject(jsonString);
JSONObject allObj = jsonObj.getJSONObject("obj");
JSONArray allArray = jsonObj.getJSONArray("all");
Jitin Kodian
  • 451
  • 4
  • 14
2

First read the data from request object :-

String jsonStr = request.getParameter("jsondata");

Use org.json library to parse it and create JsonObject :-

JSONObject jsonObj = new JSONObject(jsonStr );

Now, use this object to get your values :-

String id = jsonObj.getString("text");

You can see complete example here :-

How to parse Json in java

lalitbhagtani
  • 449
  • 5
  • 6
1

if your String data like ,

{
    "text" : "ABC",
    "msg" : "9551667858",
    "all":[
        {"name":"one"},
        {"name":"two"}
        ],
    "obj":{
        "firstname":"John",
        "lastname":"Doe"
    }
}

and It can get like,

String jsonData = request.getParameter("jsondata");

Parse to JSONObject is.

JSONObject jsonObject = new JSONObject(jsonData); // put "String"

You can get JSONArray like,

JSONArray jsonArray = jsonObject.getJSONArray("all");

good luck

botem
  • 338
  • 1
  • 11