简体   繁体   中英

Getting data from incoming JSON in a Java servlet

A client is sending me a JSON file through HTTP PUT, here is the file :

    {
    "nomPers": "Testworking",
    "prenomPers": "WorkingTest",
    "loginPers": "Work",
    "pwdPers": "Ing",
    "active": true
    },

I'm using HTTPServlet as WebService framework and the org.json library to work with Json. I'm also using Tomcat Server. As Tomcat can't create a parameter map for this HTTP verb, i've to work with JSON objects.

So I did some searching and tries but still can't make it work, here is my code :

    @Override
public void doPut(HttpServletRequest request, HttpServletResponse response) {

    // this parses the incoming json to a json object.
    JSONObject jObj = new JSONObject(request.getParameter("jsondata"));

    Iterator<String> it = jObj.keys();

    while(it.hasNext())
    {
        String key = it.next(); // get key
        Object o = jObj.get(key); // get value
        System.out.println(key + " : " +  o); // print the key and value
    }

So i'm parsing the incoming Json to a Json object to work with, then I create an Iterator to be able to loop through this object and get and and print datas for each key/value pair.

The problem is I get a NullPointerException error.

I guess it's because of the request.getParameter("jsondata"). It seems I don't get any parameters. I guess i've to create a string from the datas i get through the request to feed the JSONObject constructor, but i don't get how to achieve this.

I think the client send JSON data to you in the body of the request, not in a parameter. So the parameter that you try to parse as JSON data will be always null . To accomplish your task, you have first of all to get the body request and then parse it as JSON. For example, you can convert the body into a String with a method like this:

public static String getBody(HttpServletRequest request)  {

    String body = null;
    StringBuilder stringBuilder = new StringBuilder();
    BufferedReader bufferedReader = null;

    try {
        InputStream inputStream = request.getInputStream();
        if (inputStream != null) {
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            char[] charBuffer = new char[128];
            int bytesRead = -1;
            while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                stringBuilder.append(charBuffer, 0, bytesRead);
            }
        } else {
            stringBuilder.append("");
        }
    } catch (IOException ex) {
        // throw ex;
        return "";
    } finally {
        if (bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (IOException ex) {

            }
        }
    }

    body = stringBuilder.toString();
    return body;
}

So, your method will become:

@Override
public void doPut(HttpServletRequest request, HttpServletResponse response) {
  // this parses the incoming JSON from the body.
  JSONObject jObj = new JSONObject(getBody(request));

  Iterator<String> it = jObj.keys();

  while(it.hasNext())
  {
    String key = it.next(); // get key
    Object o = jObj.get(key); // get value
    System.out.println(key + " : " +  o); // print the key and value
  }
  ...

So apparently your client was sending json string as request body due to which you were getting null while getting it from request.getParameter("jsondata").

In this case you need to pick request body data from request.getInputStream(), so your updated method should be something like this,

@Override
public void doPut(HttpServletRequest request, HttpServletResponse response) {
    String jsonBody = new BufferedReader(new InputStreamReader(request.getInputStream())).lines().collect(
            Collectors.joining("\n"));
    if (jsonBody == null || jsonBody.trim().length() == 0) {
        // return error that jsonBody is empty
    }

    // this parses the incoming json to a json object.
    JSONObject jObj = new JSONObject(jsonBody);

    Iterator<String> it = jObj.keys();

    while (it.hasNext()) {
        String key = it.next(); // get key
        Object o = jObj.get(key); // get value
        System.out.println(key + " : " + o); // print the key and value
    }
}

Hope this helps.

Use below parser and JsonObject to get the data in the form of JsonObject.

These classes are available in gson-2.8.5.jar, import this jar and then use the gson libray.

JsonParser parser = new JsonParser();
JsonObject o = parser.parse(request.getParameter("jsondata"));

You can get the keySet from the JsonObject and then iterator it using Iterator.

Hope this will help you!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM