Getting data from incoming JSON in a Java servlet
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
}
...
How to handle JSON in POST body HttpServletRequest
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
HttpServletRequest JSON parameter found null value in Servlet
WebResource not sending the data as part of the url, so you can not use request.getParameter
. The data is send as request body using the post method.Read the data using the reader.
StringBuilder sb = new StringBuilder();
while ((s = request.getReader().readLine()) != null) {
sb.append(s);
}
JSONObject jSONObject = new JSONObject(sb.toString());
System.out.println(jSONObject.getString("commandid"));
How to read a Json object from HttpServletRequest?
The reason is that you pass the data as JSON
but you want to get it as String and invoke toString()
,but you will get null so NullPointerException will happen
So change your ajax
code to below:
$.ajax({
cache: false,
url: 'AddPPCheques.ws',
type: "POST",
data: {chequesList:JSON.stringify(myJson)},
success: function (data) {
}
}
);
Send a simple JSON object in Java to a Servlet
Your json object is not being sent as a request param, it is sent in the request body.
So, in your server side servlet you do not have to try to recover it from any request param, you must read it from the HttpServletRequest's InputStream.
Read it and then parse it using the json library you have chosen in your servlet method and you will get it.
Get JSON Data in Servlet with POST Method from Javascript not working
Problem was, that i had to remove the contentTyp in my JS file.
No it works
Related Topics
Variable Column Names Using Prepared Statements
How to Instantiate an Abstract Class
Connection Pooling Options With Jdbc: Dbcp VS C3P0
Hibernate: Hbm2Ddl.Auto=Update in Production
How to Cast a List of Supertypes to a List of Subtypes
How to Mock a Final Class With Mockito
Match Multiline Text Using Regular Expression
How to Parse Dates in Multiple Formats Using Simpledateformat
Why Do I Get "Exception; Must Be Caught or Declared to Be Thrown" When I Try to Compile My Java Code
Multiple Row Selection in Jtable
Remote Debugging a Java Application
List Contents of Multiple Jar Files
The Full Pathname of a Jdk Installation for Oracle SQL Developer
How to Add Multiple Jar Files in Classpath in Linux
Create a Java Executable with Eclipse
Installing Jdk8 on Ubuntu- "Unable to Locate Package" Update Doesn't Fix
Arval SQLexception: Fatal: Sorry, Too Many Clients Already in Postgres