How to send JSonArray to spring controller - json

how I could post jsonArray through Ajax call to the spring controller??
[{"REQUEST_ID":"BBBBBBB","MATCH_COUNT":"Accountant","CLIENT_ID":"Tokyo","MATCH_REASON":"63","NAME":"2011/07/25","FATHER_NAME":"$170,750"},{"REQUEST_ID":"CCCCCCC","MATCH_COUNT":"Junior Technical Author","CLIENT_ID":"San Francisco","MATCH_REASON":"66","NAME":"2009/01/12","FATHER_NAME":"$86,000"}]
this is my JSON array want to pass this!!
$.ajax({
type : "POST",
dataType: 'json',
contentType:'application/json',
url : "getCheckBoxData",
data : JSON.stringify(jsonData),
// data : "data="+JSON.stringify(data),
//async : false,
success : function(response) {
#RequestMapping(value = "/getCheckBoxData", method = RequestMethod.POST)
public String checkBoxData(#RequestBody List<ListOfCheckBox> value, HttpSession session

The data you are sending should match the parameter type in the controller function. What exact problem are you facing ?

Related

How to send array of json objects to spring controller using ajax

I have converted all tables into json format using the below code:
var table2 = $('#yTable').tableToJSON();
alert(JSON.stringify(table2));
How do I send these three json arrays to spring controller? In spring controller I want these json array of objects as separate params:
[
{"Label":"A","Dimension":"0"},
{"Label":"B","Dimension":"10"},
{"Label":"C","Dimension":"20"},
{"Label":"D","Dimension":"30"},
{"Label":"E","Dimension":"40"}
]
[
{"Label":"1","Dimension":"0"},
{"Label":"2","Dimension":"10"},
{"Label":"3","Dimension":"20"},
{"Label":"4","Dimension":"30"},
{"Label":"5","Dimension":"40"}]
[
{"Label":"Floor1","Dimension":"0"},
{"Label":"Floor2","Dimension":"10"},
{"Label":"Floor3","Dimension":"20"},
{"Label":"Floor4","Dimension":"30"},
{"Label":"Floor5","Dimension":"40"}
]
ajax call
$.ajax({
type: "POST",
contentType : 'application/json; charset=utf-8',
dataType : 'json',
url: "/bimspring/gridData",
data: JSON.stringify(postData),
success : function(response) {
// do something ...
},
error : function(e) {
alert('Error: ' + e);
}
});
Controller
#RequestMapping(value = "/gridData", method = RequestMethod.POST)
public #ResponseBody String getSearchUserProfiles(#RequestBody Search[] list) {
return null;
}

400 Bad Request while posting Json Object

i am trying to post jsonObject from jsp to controller and i am getting 400 Bad Request Error.
My jsp code
$.ajax({
url : 'save.web',
type: "post",
dataType: 'json',
contentType:'application/json',
data: "data="+JSON.stringify(jsonArray),
success:function(data){
}
});
});
My json Object
var jsonArray="{"+'"'+"cds"+'"'+":"+"[";
for(i=0;i<newRow.length;i++)
{
jsonArray=jsonArray+"{"+'"'+"dno" +'":'+newRow[0]+","+'"'+"CampaignCode"
+'":'+newRow[1]+"," +'"'+"CampaignName"+'":'+newRow[2]+","
+'"'+"ServiceNo" +'":'+newRow[3]+"}";
}
jsonArray=jsonArray+"]}";
My controller Code
#RequestMapping(value = "/save.web", method = RequestMethod.POST)
#ResponseBody
public String save(WebRequest webRequest,Model model,HttpServletRequest
request, HttpServletResponse response,#RequestParam CampaignDisplay[] cds)
{
for(CampaignDisplay inputs : cds){
System.out.println(inputs.getId());
}
return "menu";
}
input Json Object which i am passing is
{"cds":[{"dno":8,"CampaignCode":d,"CampaignName":e,"ServiceNo":f},
{"dno":7,"CampaignCode":a,"CampaignName":b,"ServiceNo":c}]}
I dont know why ia m getting 400 erro? i ahve set the headers also
seems the controller is not able to understand the request. The reason is "You are posting JSON, not form data, but you are trying to read as a form parameter".
change your method to
**public String save(WebRequest webRequest,Model model,HttpServletRequest
request, HttpServletResponse response,#RequestBody Map<String, Object> inputParameter)
{**
Check this link for your reference 400 Bad request on Spring Jquery Ajax Post

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);
}
});

Passing in JSON array to spring MVC Controller

I am trying to pass a JSON array into spring MVC Controller like such:
var myList = new Array();
data._children.forEach( function (d) {
myList.push( {NAME: d.name, TYPE: d.TYPE, FDATE: d.FDATE } );
});
$.post("/ListRequest", {myList: myList});
The controller looks as such:
#RequestMapping(value="/ListRequest", method = RequestMethod.POST)
public void ListRequest(#RequestParam("myList") myList tempmyList )
{
System.out.println(tempmyList);
}
The class myList defined as such:
public class MyList {
private List<ListT> ListT;
public List<ListT> getListT() {
return ListT;
}
public void setListT(List<ListT> listT) {
ListT = listT;
}
}
ListT class:
public class ListT {
private String NAME;
private String TYPE;
private Long FDATE; ...
I keep getting this error:
HTTP Status 400 - Required myList parameter 'myList' is not present
Also tried this request:
$.ajax({
type: "post",
url: "ListRequest", //your valid url
contentType: "application/json", //this is required for spring 3 - ajax to work (at least for me)
data: JSON.stringify(myList), //json object or array of json objects
success: function(result) {
//do nothing
},
error: function(e){
alert('failure');
}
but get this error: JBWEB000120: The request sent by the client was syntactically incorrect.
try to add this to you ajax call it should fix the unsupported response :
headers : {
'Accept' : 'application/json',
'Content-Type' : 'application/json'
},
this is a full example of ajax call that is working for me :
$.ajax({
dataType : "json",
url : this.baseurl + "/dataList",
headers : {
'Accept' : 'application/json',
'Content-Type' : 'application/json'
},
data : JSON.stringify(params),
type : 'POST',
success : function(data) {
self.displayResults(data);
},
error : function(jqXHR,textStatus,errorThrown ){
showPopupError('Error','error : ' + textStatus, 'ok');
}
});
Even I was facing same problem.
My client request was right and generated proper json file.
but still i was getting same error.
I solved this error using #JsonIgnoreProperties(ignoreUnknown = true) in pojo class.
refer this link.
Spring MVC : The request sent by the client was syntactically incorrect
You can try
#RequestParam("myList") myList tempmyList
#Param myList tempmyList
in addition, class names must begin with a capital letter.

Send generic JSON data to MVC2 Controller

I have a javascript client that is going to send json-formatted data to a set of MVC2 controllers. The client will format the json, and the controller will have no prior knowledge of how to interpret the json into any model. So, I can't cast the Controller method parameter into a known model type, I just want to grab the generic json and pass it to a factory of some sort.
My ajax call:
function SendObjectAsJSONToServer(object,url,idForResponseHTML) {
// Make a call to the server to process the object
var jsonifiedObject = JSON.stringify(object);
$.ajax({
url: url // set by caller
, dataType: 'json'
, data: jsonifiedObject
, type: 'GET'
, error: function(data) { alert('error in sendObjectAsJSONToServer:' + data); }
, success: function(data) {
alert(data.message); // Note that data is already parsed into an object
}
});
}
My MVC Controller:
public ActionResult SaveForm(string obj)
{
// Ok, try saving the object
string rc = PassJSONToSomething(obj.ToString());
string message = "{\"message\":\""+rc+"\",\"foo\":\"bar\"}";
return new ContentResult { Content = message, ContentType = "application/json" };
}
The problem is that obj is always null. Can anyone tell me how I should structure the ajax call and the controller parameter so that I get my json to the server? I'm using MVC2. This may appear to be a duplicate of some SO questions, but in my case I do not know the Model that the json maps to, so I can't use a specific model type in the controller parameter type.
Thanks very much.
Have you tried something like that?
$.ajax({
url: url // set by caller
, dataType: 'json'
, data: {obj :jsonifiedObject}
, contentType: 'application/json; charset=utf-8'
, type: 'GET'
, error: function(data) { alert('error in sendObjectAsJSONToServer:' + data); }
, success: function(data) {
alert(data.message); // Note that data is already parsed into an object
}
});