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

4 Answers4

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
  • 471
  • 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
  • 459
  • 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
  • 348
  • 1
  • 11
0

I think it's too late but : Here method I use from other stackoverflow users, And I don't remember which post is it. From Javascript you can use method like this :

    let xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        if (this.readyState != 4) return;

        if (this.status == 200) {
            alert(this.responseText);
            var data = JSON.parse(this.responseText);


        }
    };

    xhr.open("POST", url, true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.send(JSON.stringify({answers}));

Than from Server in Servlet you just need read all content with this method and after that grab data you need.

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.json.HTTP;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;

@WebServlet(name = "T", value = "/T")
public class WebExam extends HttpServlet {
       @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        JSONObject resp = new JSONObject();


        StringBuffer jb = new StringBuffer();
        String line = null;
        try {
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null)
                jb.append(line);
        } catch (Exception e) { /*report an error*/ }

        try {
            JSONObject jsonObject = HTTP.toJSONObject(jb.toString());
            response.getWriter().println(jsonObject.toString());
        } catch (JSONException e) {
            // crash and burn
            response.getWriter().println("unknown!");
        }
}