How to read a Json object from HttpServletRequest? - json

I'm sending a json object from a ajax call to java.
$.ajax({
cache: false,
url: 'AddPPCheques.ws',
type: "POST",
contentType: "application/json",
dataType: "json",
data: "chequesList=" + JSON.stringify(myJson),
success: function (data) {
}
}
);
Browser Console ->
chequesList=[{"Bank Code":"4234-322","Cheque No":"23432232","Amount":"432432","Commission":"427","Today":"2018-06-08"},{"Bank Code":"4234-112","Cheque No":"778787","Amount":"8986787","Commission":"2323","Today":"2018-06-08"}]
In java side im trying to read it from a HttpServletRequest.
public ActionForward addCheques(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
JSONObject myResponse = new JSONObject ( request.getParameter("chequesList").toString() );
}
But I get a NullPointerException. What am I doing wrong here? And how to read the json object details?

The reason is that you pass the data as JSON but you want to get it as String and invoke toString(),but you will get null so NullPointerException will happen
So change your ajax code to below:
$.ajax({
cache: false,
url: 'AddPPCheques.ws',
type: "POST",
data: {chequesList:JSON.stringify(myJson)},
success: function (data) {
}
}
);

Related

how to pass serialize data and stringified data together in ajax

I have a ajax function where i am passing two objects:
1) serialize form data object
2) complex object
Ajax function:
var temp = sessionStorage.getItem('book');
var viewName = $.parseJSON(temp);
var ViewModel = $("#OffsetBookForm").serialize();
$.ajax({
contentType: "application/json; charset=utf-8",
type: "Post",
url: "#Url.Content("~/Estimate/CreateOrder")",
data: JSON.stringify({ 'OffsetCommonObj': ViewModel, 'obj': viewName }),
dataType: 'json',
success: function (data) {
}
});
And My ActionMethod:
public ActionResult CreateOrder(EstimationOffsetViewModel OffsetCommonObj,
OffsetCostCalculation obj)
{
// do something here..
}
My problem is, the first object in action method i.e-"OffsetCommonObj" is getting null. What am I doing wrong in the code? Please Help..Thanks.

how to return json from groovy please?

My environment is openjdk version "1.7.0_75", tomcat-7.0.82, groovy-2.4.13, jquery-3.2.1.
Now I want use ajax post some data to groovy, and want groovy return json to ajax.
Ajax:
$.ajax({
type: "post",
contentType: "application/json; charset=UTF-8",
url: "edit.groovy",
data: json,
dataType: 'json',
success : function(data) {
console.log('ok');
},
error: function(data) {
console.log('err');
}
});
And edit.groovy:
response.contentType = 'application/json';
out << "{rs: 2}";
My question is, why the log is 'err', is my groovy return a right json type please? How to fix it please?
"{rs: 2}"
Isn't valid json the name had to be in double quotes
'{"rs": 2}'
Just use a builder with a map, and it will be done for you
new JsonBuilder([rs: 2]).toString()

Return json array from client to spring controller

I need to send data from the client html back to the spring controller.
I have a controller which generates a Json array whichh I sent via ajax to the html side when requested.
That functions well.
The Problem is I need to send the Json array back to another controller for evaluation and changes.
If I post the data and assign an class object of the original class I get the error " Bad request" and it didn't work.
If I assign an object in the controller which consumes the post. That works
but I get an hashmap for which I dont know how to access.
I cant cast it to another class nor access it to work with it.
Since I am new to this can someone give me an advice how to consume the post
on the receiving controller side.
Thanks
Khelvan.
Controller code ist stated below
controller 1 for Get
#RequestMapping("/Person")
#ResponseBody
public ArrayList<Person> ajax_Person_array()
{
ArrayList<Person> Dummy = new ArrayList<Person>();
for ( x=0; x < 5; x++ ){
Dummy.setName("Alfon");
Dummy.setID("5");
Dummy.setStree("Delta");
Dummy.setName("Neutral");
Person.add(Dummy);
}
return Dummy;
}
Controller 2 for post
#RequestMapping(value="/ajax", method=RequestMethod.POST, consumes = "application/json")
//public #ResponseBody String post( #RequestBody Object ajax_Person_array()) {
public #ResponseBody String post( #RequestBody ArrayList<Person> ajax_Person_array()) {
System.out.println("First TEST");
String Success = "OK";
return Success;
}
Html : get ajax
var ajax_data;
$.ajax({
url: "http://localhost:8080/Person",
async: false,
dataType:'json',
cache: false,
success: function (data) {
ajax_data = data;
alert("success ");
},
error:function(){alert("something went wrong ");}
});
}
Html post ajax
$.ajax({
url: "http://localhost:8080/ajax",
type: 'POST',
dataType: 'text',
data: ajax_data,
// data: JSON.stringify(ajax_data),
contentType: 'application/json',
success: function(data) {
alert(data);
},
error:function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er);
document.write(data);
}
});
#RequestMapping (value="/ajax", method=RequestMethod.POST, consumes = "application/json")
public #ResponseBody JSONObject post( #RequestBody JSONObject person) {
//Pass data to a service to process the JSON
}
For your ajax request, do not set dataType to 'Text'. Set it to JSON
$.ajax({ url: "http://localhost:8080/ajax",
type: 'POST',
dataType: 'json',
data: JSON.stringify(ajax_data),
contentType: 'application/json',
success: function(data) {
alert(data);
},
error:function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er);
document.write(data);
}
});

JSON passed to controller has no value

I am unable to get my JSON to my controller, and I can't figure out why the value I get in javascript isn't being passed to the controller. Here is my ajax post in my javascript:
this.save = function () {
var data = ko.toJSON(this.Routines);
$.ajax({
type: 'POST',
url: "CreateJson",
data: data,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
if (!result.success)
alert("test")
else { }
}
})
}
now data contains
[{"routine_name":"new routine","duration":"20","rest":"10","rounds":1}]
which is what I want, but the controller shows nothing. Here is my controller
[HttpPost]
public JsonResult CreateJson(t_routine routine, string data)
{
var message = "success";
return Json(message);
}
As I understand it, MVC 3+ automatically receives JSON without any need for parameters like my string data, I just threw it in there to try and figure out if I'm getting anything at all. data is null and routine shows 0's and null for values. What am I missing?
If t_routine represents the server side type for
[{"routine_name":"new routine","duration":"20","rest":"10","rounds":1}]
Then it might be enough to call JSON.stringify on the ko.toJSON result like this
this.save = function () {
var data = JSON.stringify(ko.toJSON(this.Routines));
$.ajax({
type: 'POST',
url: "CreateJson",
data: data,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
if (!result.success)
alert("test")
else { }
}
})
}
the data parameter on your controller action is not needed then and you most likely need to change the t_routine parameter to t_routine[]

how tosend unlimited json data from jquery ajax to mvc razor controller

I have to send unlimited JSON data from ajax J query to MVC razor controller.
The method is triggered once we send limited data. if i send more data the method is not triggered and Am getting 500 Internal error.
$.ajax({
url: '../Offline/Save',
data: JSON.stringify(Item),
data: "{'Id':" + Results.rows.item(m).Id + ",'Item':" + JSON.stringify(Item) + "}",
type: 'POST',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data, status) {
alert(data);
}
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(thrownError);
}
});
[HttpPost]
[ValidateInput(false)]
public JsonResult SaveFinding(int Id, SyncItem Item)
{
Result result = new DB().Process(Id, Item);
return Json(result);
}
have you tried debugging ?
Is the method SaveFinding() itself not throwing the error ?
Or is it after the method is completed you are getting the error ?
Here are a few links that you should consider looking at
Can I set an unlimited length for maxJsonLength in web.config?
http://binoot.com/2008/10/14/using-json-some-observations/
http://support.microsoft.com/kb/981884
http://dotnetbyexample.blogspot.com/2007/11/expanding-lenght-of-json-data-returned.html