2

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.

3
  • 1
    unless jsondata param is passed from client end, you will get it null only. You should first ensure that jsondata is not null before creating object like the way you did. Commented Oct 12, 2018 at 4:54
  • Try setting content type as application/json in your PUT response and then check the above code. Commented Oct 12, 2018 at 5:03
  • @PushpeshKumarRajwanshi Yes you are right, it would have been better to test it before. The main problem here was i was getting parameters from the body and not the URI. Commented Oct 12, 2018 at 9:07

3 Answers 3

4

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
  }
  ...
Sign up to request clarification or add additional context in comments.

8 Comments

I think this is exactly what i need. According to the test code below, i don't get any parameters and the client seems to send JSON datas in the body of the request like you said. I'll test your code right now and keep you updated, but it's a big step forward, thanks !
I hope it helps you! :).
I'm struggling with some "Unreported exception java.io.IOException exception; must be caught or declared to be thrown." errors. I don't really get why as Exceptions seems to be correctly set up. I'll try to make it work.
I slightly change the code: if IOException will occur, the method will return an "" string.
For getting json data instead of writing that big method, you can do this, String jsonData = new BufferedReader(new InputStreamReader(inputStream)) .lines().collect(Collectors.joining("\n"));
|
1

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.

Comments

-1

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!

2 Comments

Doing like this with gson libray will only do the same work i do with org.json, but not solve the problem i had as far as i know. Or am i wrong ?
@Ishiru Oh right! here you don't need that, seems like you need to get the proper json data first. I think reading it from the inputStream as body as suggested in above answer should solve your problem.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.