I'm attempted to pull parameters from JSON in a POST request. This seems like a very basic process and I've read through numerous posts about this but I'm missing something here as I'm getting an object back but the fields within that object are null. In my POST I have the following JSON...
{
"client": "1",
"forTopic": "topic"
}
And here is my POST method inside my servlet...
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String requestBody = RESTUtil.getRequestBody (request);
log.debug (requestBody);
try
{
JAXBContext context = JAXBContext.newInstance (ClientAndTopicParameters.class);
Unmarshaller unmarshal = context.createUnmarshaller ();
unmarshal.setProperty (UnmarshallerProperties.MEDIA_TYPE, "application/json");
unmarshal.setProperty (UnmarshallerProperties.JSON_INCLUDE_ROOT, true);
ClientAndTopicParameters params = (ClientAndTopicParameters) unmarshal.unmarshal (new StreamSource (new StringReader (requestBody)), ClientAndTopicParameters.class).getValue ();
log.debug ("params = " + params);
log.debug ("client = " + params.client);
log.debug ("forTopic = " + params.forTopic);
}
catch (JAXBException e)
{
log.error ("Unable to get Client and Topic parameters from POST.", e);
}
}
Finally, here is my ClientAndTopicParameters class...
@XmlRootElement
public class ClientAndTopicParameters
{
@XmlElement public String client;
@XmlElement public String forTopic;
}
The resulting output is the following...
2018 Aug 24 17:44:55,806 DEBUG [MyServlet ] params = mypackage.ClientAndTopicParameters@2995a298
2018 Aug 24 17:44:55,806 DEBUG [MyServlet ] client = null
2018 Aug 24 17:44:55,806 DEBUG [MyServlet ] forTopic = null
As you can see this pretty basic stuff. I'm assuming I'm missing something small that I'm just not seeing. Welcome any thoughts and insights. For reference I'm using JAXB v2.3.0
The solution is to serialize your desired object and play with the includeRoot flag. If you set it to false, you will get the desired output.
I used these dependencies:
In your code, this is the only thing you have to change: