1

I am very new to servlet and I am unable to read JSON array from HttpServletRequest

I am sending below JSON to Java

page: 1
start: 0
limit: 20
sort: [{"property":"fiscalYear","direction":"DESC"}]
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        String[] s=request.getParameterValues("sort");
        for(int i=0;i<s.length;i++)
}           System.out.println(s[i]);

actual output

 [{"property":"fiscalYear","direction":"DESC"}]

expected output get values fiscalYear and DESC separately

1
  • Use this to generate a domain model class : jsonutils.com then use ObjectMapper to convert the json to an object Commented Jun 9, 2019 at 9:08

3 Answers 3

1

getParameterValues(String name) will return the String array

String[] getParameterValues(String name)

Returns an array of String objects containing all of the values the given request parameter has, or null if the parameter does not exist.

If the parameter has a single value, the array has a length of 1.

getParameter(String name) will return only String

Returns the value of a request parameter as a String, or null if the parameter does not exist. Request parameters are extra information sent with the request. For HTTP servlets, parameters are contained in the query string or posted form data.

You should only use this method when you are sure the parameter has only one value. If the parameter might have more than one value, use getParameterValues(java.lang.String).

Based on this you can go for getParameter which returns JSON representing string

String s=request.getParameter("sort"); // {"property":"fiscalYear","direction":"DESC"}

Now use ObjectMapper to read parse the JSON string

ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(s);
String property = jsonNode.get("property").asText();
String direction = jsonNode.get("direction").asText();

If it is Array of JsonObjects //[{"property":"fiscalYear","direction":"DESC"}]

JsonNode jsonNode = objectMapper.readTree(s);
JsonNode node = jsonNode.get(0);
String property = node.get("property").asText();
String direction = node.get("direction").asText();
Sign up to request clarification or add additional context in comments.

Comments

1
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        String str=request.getParameterValues("sort");
    //  str=" [{\"property\":\"fiscalYear\",\"direction\":\"DESC\"}]";   
      JSONArray array=new JSONArray(str);
      for(int i=0;i<array.length();i++){
              JSONObject json_obj = array.getJSONObject(i);
            System.out.println( json_obj.getString("direction"));

      }
} 

OUTPUT

DESC

Comments

0

You can create an Object which hold this infor :

public class SortDto {

  private String property;
  private String direction;

  // getters, setters, toString() ..
}

Then create an ObjectMapper like this :

ObjectMapper mapper = new ObjectMapper();
String sortJson = request.getParameter("sort");
// I suppose that sortJson is => {"property":"fiscalYear","direction":"DESC"}
SortDto dto = mapper.readValue(sortJson, SortDto.class);

Then you can just override the toString() method in your class or call dto.getProperty() dto.getDirection() to get the values separately.


Note

I used request.getParameter("sort") which return one String instead of request.getParameterValues("sort") which return an array of values

2 Comments

It is an array [ {"property":"fiscalYear","direction":"DESC"}]
@AnmolDuggal even with [ {"property":"fiscalYear","direction":"DESC"}] my solution works fine, I test both of them and both work fine

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.