Alexander  Tolkachev Alexander Tolkachev - 5 months ago 10
JSON Question

Passing Json data to servlet response

How can i pass Json object to servlet response writer? I want to pass json data to ajax function. But it gives me parsing exception



$(document).ready(function(){
$(".count").on('blur', function(){
var pack_count = $(this).val();
var order_id = $(this).attr('id');
$.post("order?action=update_counter&pack_count=" + pack_count + "&order_id=" + order_id, function(data){
alert("Change is successfull! Price: ");
$("#sum").html("Order Price: " + data);
var price = data['order_sum'];
var pack_count = data['pack_count'];
document.getElementById('price').value = price;
$(this).val(pack_count);
})
});
});





resp.setContentType("application/json; charset=UTF-8");
PrintWriter out = resp.getWriter();
String jsonData = "{ \"pack_count\" : \"" + selectedOrder.getPackageCount() + "\", \"order_sum\" : \"" + countSum() + "\" }";

out.print(jsonData);


Update:



Solved it! Thanks to printfmyname

and backslash comments. Just changed jsonData to

String jsonData = "{ " + "\"pack_count\" : " + selectedOrder.getPackageCount() + ", \"order_sum\" : " + countSum() + " }";

Answer

You are wring a json string to output but your header is by default set to text/html or something that is not json. So you need to set proper header before writing to output

response.setContentType("application/json; charset=UTF-8"); # you may get rid of ; charset=UTF-8 as it is not critical 

Then when you done writing to output call

 out.flush();

Update:

You have an error on

String jsonData = "{ \"pack_count\" : \"" + selectedOrder.getPackageCount() + ", \"order_sum\" : " + countSum() + " }"; 

you a missing a quotation after selectedOrder.getPackageCount() , change to follwong

String jsonData = "{ \"pack_count\" : \"" + selectedOrder.getPackageCount() + "\", \"order_sum\" : " + countSum() + " }";