1

I want to transfer potentially large, nested JSON between Browser Javascript (JS) and my Java servlet. I am able to pass JSON from Java to JS but not from JS to Java servlet. I get the error:

Can not deserialize instance of java.util.LinkedHashMap out of START_ARRAY token

Also, I am not sure I am going from Java to JS correctly. Here is my JS code:

        var xmlhttp;
        if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {// code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange=function() {
            if (xmlhttp.readyState==4 && xmlhttp.status==200) {
                var response = JSON.parse(xmlhttp.responseText);
                var x = 1;
            }
        }
        xmlhttp.open("POST", 'http://localhost:8084/MyApp/JavaScriptInterface', true);
        xmlhttp.setRequestHeader("Content-type","application/json");
        xmlhttp.send({name: 'dog'});

Here is my Java code:

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    ObjectMapper mapper = new ObjectMapper();


    // get data passed in

    @SuppressWarnings("unchecked")
    Map<String,Object> inData = mapper.readValue(request.getInputStream(), Map.class);

    // send data

    response.setContentType("application/json");

    Map<String,Object> dat = new HashMap<>();
    dat.put("fname", "Tom");
    dat.put("lname", "Jones");
    dat.put("age", 36);

    PrintWriter out = response.getWriter();
    mapper.writeValue(out, dat);
}

I think there is more than one way to do this, but I must be able to support larger, nested JSON objects.

Thanks for the help!

Blake McBride

Blake McBride
  • 394
  • 3
  • 16

2 Answers2

0

rFor the server side, have you tried Jersey's JSON support? If you're using Maven, this is something to get you started.

@POST
@Path("/JavaScriptInterface")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Map<String,String> handlePost(Map<String,String> inData) {
     Map<String,Object> dat = new HashMap<>();
     dat.put("fname", "Tom");
     dat.put("lname", "Jones");
     dat.put("age", 36);
     return dat;
}

Also for the client side, you should check into using jQuery. Here is a stack overflow answer.

 var data = JSON.stringify({name: 'dog'});
 $.ajax({
    type: "POST",
    url: 'http://localhost:8084/MyApp/JavaScriptInterface',
    dataType: 'json',
    data: data,
    success: function (responseData) {
        // this prints out your data
        console.log("successful", responseData);
    }
 })
Community
  • 1
  • 1
tom
  • 1,331
  • 1
  • 15
  • 28
0

I think I got it to work by changing one line of the JS file to:

xmlhttp.send(JSON.stringify({name: 'dog'}));
Blake McBride
  • 394
  • 3
  • 16