Issue
I have a REST Java app based on servlets and I would like to manage requests like that:
curl -X POST -d "[{"label": "001", "value": 12345}, {"label": "002", "value": 54321}]" -H 'Content-Type: application/json' xxx.com/my/endpoint
Basically I'm sending a JSON array and the question is how can I properly parse it? All I got at this moment was printing it using something like that:
String body = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
But I want to be able to handle every pair of label and value from the request.
Solution
Solution org.json and org.apache.commons.io
The simplest solution is probably doing the following
- Convert input stream to string
- Populate JSONArray with string using constructor
- Loop through the array
- For each interation grab the JSONObject from that iteration of the array
- Grab the value of the member from the current object
You could also map the String to a set of classes that match the JSON Schema using JSON. This is more complicated but it may be an alternate solution. The biggest issue with that may be how to map an top level anonymous array to a class
String string = IOUtils.toString( request.getInputStream() );
JSONArray jsonArr = new JSONArray( string );
JSONObject object;
for ( int i = 0; i < jsonArr.length(); i++ ) {
object = jsonArr.getJSONObject( i );
System.out.println( object.getString("label") );
System.out.println( object.getInt("value") );
}
You will need to add the org.json
and org.apache.commons.io
dependency to your build path. The following is a sample of how to add it to your project via Maven
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20210307</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
Post Script
You stated this solution is stripping the leading zeros off the value of the label property. I believe this has to do with your request, not the code sample. Try to either escape the nested double quotes or use single quotes
curl -X POST -d '[{"label": "001", "value": 12345}, {"label": "002", "value": 54321}]' -H 'Content-Type: application/json' xxx.com/my/endpoint
I believe the nested double quotes are causing the JSON to treat the value of the label property as numeric
Answered By - Chris Maggiulli