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