Receiving JSON data from POST

643 views
Skip to first unread message

Al Grant

unread,
Feb 28, 2017, 7:18:38 PM2/28/17
to jackson-user
Hello,

I am having trouble receiving JSON data from an HTML form and mapping it into a Java Object.

The line that is causing me error is:

        Episode episode = mapper.readValue(json , Episode.class);

Which results in: HTTP Status 500 - Unrecognized token 'start_date': was expecting ('true', 'false' or 'null')

Some background about the code:

A snippet of my Episode Class:

package com.fh;

public class Episode {

   
private String start_date;
   
private String end_date;
   
private String report_date;
   
private String attend_date;
   
private String proximity;...

   
public String getProximity() {
       
return proximity;
   
}

   
public void setProximity(String proximity) {
       
this.proximity = proximity;

etc
.....


And the servlet class:

Enter code here..@WebServlet(name = "newfh", urlPatterns = {"/form"})

public class cmfhapp extends HttpServlet {
   
   
@Override
   
protected void doGet(HttpServletRequest request, HttpServletResponse response)
           
throws ServletException, IOException {
       
System.out.println("doGet hit");
        request
.getRequestDispatcher("/index1.jsp").forward(request, response);
   
}

   
@Override
   
protected void doPost(HttpServletRequest request, HttpServletResponse response)
           
throws ServletException, IOException {

       
//  GET RECEIVED JSON DATA
       
BufferedReader br = new BufferedReader((new InputStreamReader(request.getInputStream())));
       
String json = "";
       
if (br != null) {
            json
= br.readLine();
       
}

       
System.out.println("Print proximity Value " +request.getParameter("proximity"));
       
ObjectMapper mapper = new ObjectMapper();
       
Episode episode = mapper.readValue(json , Episode.class);
       
System.out.println(episode.getProximity());

       
System.out.println("doPost hit");
        request
.getRequestDispatcher("/login.html").forward(request, response);
   
}
}.

The JSON data is being sent from the form with:



$
.fn.serializeObject = function()
{
   
var o = {};
   
var a = this.serializeArray();
    $
.each(a, function() {
       
if (o[this.name] !== undefined) {
           
if (!o[this.name].push) {
                o
[this.name] = [o[this.name]];
           
}
            o
[this.name].push(this.value || '');
       
} else {
            o
[this.name] = this.value || '';
       
}
   
});
   
return o;
};
 
<script>
    $
(document).ready(function() {
       
// click on button submit
        $
("#submit").on('click', function(e){
       
// send ajax
        $
.ajax({
            url
: "form", // url where to submit the request
            type
: "POST", // type of action POST || GET
            dataType
: "json", // data type
            data
: JSON.stringify($('#formfv').serializeObject()), // post data || get data
            contentType
: "application/json",
            success
: function(result) {
                console
.log(result);
           
},
            error
: function(xhr, resp, text) {
                console
.log(xhr, resp, text);
           
}
       
})
   
});
   
});
</script>

I think the JSON data is being received correctly as the value of json when printed in console looks like:

{
   
"start_date": "",
   
"end_date": "",
   
"report_date": "",
   
"attend_date": "",
   
"proximity": "Nearby",
   
"locationtype": "",
   
"reported_by": "Family",
   
"location": "",

And this validates on JSO linter.

So why am I getting: HTTP Status 500 - Unrecognized token 'start_date': was expecting ('true', 'false' or 'null')

Cheers

Al
 

Al Grant

unread,
Feb 28, 2017, 8:55:11 PM2/28/17
to jackson-user
The full error in the browser is :


HTTP Status 500 - Unrecognized token 'start_date': was expecting ('true', 'false' or 'null')

type Exception report

message Unrecognized token 'start_date': was expecting ('true', 'false' or 'null')

description The server encountered an internal error that prevented it from fulfilling this request.

exception

com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'start_date': was expecting ('true', 'false' or 'null')
 at [Source: start_date=28%2F02%2F2017+14%3A01&end_date=01%2F03%2F2017+14%3A03&report_date=01%2F03%2F2017+14%3A03&attend_date=01%2F03%2F2017+14%3A03&proximity=Outside&locationtype=Commercial&reported_by=Neighbour&location=&b_station=Akaroa&a_station=Addington+CCB&weapon=BD&alcohol=&drugs=&firearms=&unborn=&surname=&address=&firstname=&gender=&dob=&ethnicity=&ethnicity=&Supervisor_id=&ethnicity=&ethnicity=; line: 1, column: 11]
	com.fasterxml.jackson.core.JsonParser._constructError(JsonParser.java:1702)
	com.fasterxml.jackson.core.base.ParserMinimalBase._reportError(ParserMinimalBase.java:558)
	com.fasterxml.jackson.core.json.ReaderBasedJsonParser._reportInvalidToken(ReaderBasedJsonParser.java:2835)
	com.fasterxml.jackson.core.json.ReaderBasedJsonParser._handleOddValue(ReaderBasedJsonParser.java:1903)
	com.fasterxml.jackson.core.json.ReaderBasedJsonParser.nextToken(ReaderBasedJsonParser.java:749)
	com.fasterxml.jackson.databind.ObjectMapper._initForReading(ObjectMapper.java:3834)
	com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3783)
	com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2842)
	com.fh.cmfhapp.doPost(cmfhapp.java:42)
	javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
	javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
	org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

note The full stack trace of the root cause is available in the Apache Tomcat/8.5.4 logs.


Apache Tomcat/8.5.4

Tatu Saloranta

unread,
Feb 28, 2017, 9:56:48 PM2/28/17
to jackson-user
Looking at the exception output, interesting part is this:

at [Source: start_date=28%2F02%2F2017+14%3A01&end_date=01%2F03%2F2017+14%3A03&report_date=01%2F03%

which gets printed because input comes as a String (otherwise wouldn't
print, although Jackson 2.9 does improve on this a bit). So input that
is been given looks like URL query String and NOT as JSON content.

It has been a while since I worked on javascript so I can't offhand
see what would cause this to happen; I think some form submit modes
would just send things as form encoded, and not as specified payload.

-+ Tatu +-
> --
> You received this message because you are subscribed to the Google Groups
> "jackson-user" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to jackson-user...@googlegroups.com.
> To post to this group, send email to jackso...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages