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

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

Related

How to send JSonArray to spring controller

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 ?

Spring Rest Controller POST request doesn't work with Ajax Json Array payload

I am getting 404 not found error while sending post request with json payload . At backend I am using spring rest controller .
Please find the code below .
#RequestMapping(value = "/api/testEnvironment/update", method = RequestMethod.POST , consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> updateEnvironment(#RequestParam("ids") String[] ids, #RequestParam("name") String name) {
System.out.println(ids);
return new ResponseEntity<>(HttpStatus.OK);
}
And Jquery function for above rest controller :-
function testing(){
var a = [] ;
a.push('a');
a.push('b');
var b = '23';
var search = {
"ids" : a,
"name" : b
}
$.ajax({
type : "POST",
url : "api/testEnvironment/update",
contentType: "application/json",
data: JSON.stringify(search),
traditional: true,
success : function(data) {
},
error : function(e) {
}
});
}

Spring MVC + Ajax error 400

I have a simple java application on Spring MVC and I send ajax request to Spring controller. When I set headers "Accept", "application/json" and "Content-Type", "application/json;charset=utf-8" in AJAX call I get error 400 in dubugger, when I delete it I get error 415.
If I change controller method signature to public String logoutPage (#RequestBody String obyavleniye) I get JSON string. What problem can be with parse request in controller?
JS method:
$("#advertForm").submit(function(e) {
e.preventDefault();
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
var obyavleniye = {
title: "Title",
price: "80",
description: "desc",
date: "2016-11-07 18:30:21",
authorid: "2",
category: "A",
state: "new",
img1: "http",
img2: "http",
img3: "http",
img4: "http",
};
var post_data = JSON.stringify(obyavleniye);
console.log(post_data);
$.ajax({
url : "/upload",
type: "POST",
dataType: 'json',
data: post_data,
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json;charset=utf-8");
xhr.setRequestHeader(header, token);
},
complete: function() {
console.log("Sent");
},
success: function (response) {
console.log("success");
console.log("response" + response);
},
error: function (data) {
console.log("error");
console.log(data);
}
});
});
Controller method:
#ResponseBody
#RequestMapping(value="/upload", method = RequestMethod.POST)
public String logoutPage (#RequestBody Advert obyavleniye) {
// public String logoutPage (#RequestBody String obyavleniye) {
System.out.println("Enter: " + obyavleniye);
this.advertService.addAdvert(obyavleniye);
// return "{\"msg\":\"success\"}";
return "{\"title\":\"Title\",\"price\":\"80\",\"description\":\"normm\",\"date\":\"2016-11-07 18:30:21\",\"authorid\":\"2\",\"category\":\"A\",\"state\":\"new\",\"img1\":\"http\",\"img2\":\"http\",\"img3\":\"http\",\"img4\":\"http\"}";
}
My sample code.
js
Company.prototype.saveCompanyLocation = function() {
/* company */
var companyIdx = $('#companyIdx').val();
var locationIdx = $('#locationIdx').val();
var data = {
idx : locationIdx,
postCode : $('#postCode').val(),
address : $('#address').val(),
detailAddress : $('#detailAddress').val(),
tel : $('#tel').val(),
fax : $('#fax').val(),
email : $('#email').val(),
language : $("#language").val(),
latitude : $('#latitude').val(),
longtitude : $('#longtitude').val()
};
data = JSON.stringify(data);
$.ajax({
url : "/gpim/company/settings/location/save/" + companyIdx,
type : 'POST',
data : data,
contentType : 'application/json',
success : function(response) {
if (response == "success") {
document.location.reload(true);
} else {
$("#editMsg").text("you can`t save location information.");
}
},
error : function(request, status, error) {
}
});
};
controller
#RequestMapping(value = "/settings/location/save/{companyIdx}", method = RequestMethod.POST)
public #ResponseBody String saveLocation(#PathVariable int companyIdx, #RequestBody CompanyLocation location) {
Company company = companyService.findCompanyByIdx(companyIdx);
company = companyService.saveCompanyLocation(company, location);
if (company != null) {
return "success";
}
return "fail";
}
Do the below steps:
1) try to keep the jackson jar files in your classpath
2) eighter you have remove the datatype while sending ajax request i.e,
dataType : "json"
or you have to produce the application/json response as below
#RequestMapping(value = "/upload", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
3) Check your DTO or Advert class properties which type should be matched with incoming request. i.e request params should match with DTO members both names and type.
These are possible ways to avoid your case.

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.