how to send cascade data from json to spring controller - json

I'm trying to send cascade data from json to spring controller. My tables are like below.
public class B implements java.io.Serializable {
private int id;
private A a;
private String name;
//getters and setters
}
public class A implements java.io.Serializable {
private String id;
private String name;
private Set Bs = new HashSet(0);
}
In my jsp code I have made 3 B and I want to save them when I'm saving my A. As you see I have hashset of Bs in my A model.
Here is my question - how can I fill my A with this 3 B's and send A via json then receive it from controller an save A and Bs by one query?
I have already tried this way but I failed:
Here is my json code:
var data = {
'id': 13,
'name': "a1",
'B':[{'name':"b1"},{'name':"b2"},{'name':"b3"}],
};
$.ajax({
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
type: "POST",
url: contexPath + A/Save.json,
data: JSON.stringify(data),
dataType: "json",
async: false,
.
.
.
}
and my controller is :
#RequestMapping(method = RequestMethod.POST, value = "/Save")
public #ResponseBody
String Save(#Valid #RequestBody A a, BindingResult result) {
iAService.addA(A);
}
Thank you.

Related

Sending a JSON list to Spring controller results in null value

I have a #RestController with an endpoint of method=POST.
I'm sending a JSON of type:
{"dataList":[
{
"id":5,
"nickname":"START",
"percent":0.92,
"weight":55.33,
"price":9679.57
},
{...},
{...}
]
}
from my ReactJs function using the fetch API like this:
const response = fetch('http://localhost:8080/myapp/api/my/test', {
method: 'POST',
mode: 'no-cors', // no-cors, *cors, same-origin
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
dataList: postData
})
});
On the backend side there's my endpoint action:
#RequestMapping(method = RequestMethod.POST, value = "api/my/test")
public ResponseEntity test(TestListDto dataList) {
/** NOTE: The endpoint is hit successfuly but the dataList INTERNAL LIST is null**/
// dataList here is a valid object
// dataList.getDataList() though is NULL !
/** some business logic**/
return new ResponseEntity(HttpStatus.OK);
}
public class TestListDto {
private List<TestDto> dataList; // THIS IS NULL WHEN ENDPOINT IS HIT
public PaymentListDto(List<TestDto> dataList) {
super();
this.dataList = dataList;
}
public List<TestDto> getDataList() {
return dataList;
}
public void setDataList(List<TestDto> dataList) {
this.dataList = dataList;
}
}
public class TestDto {
private Long id;
private String nickname;
private BigDecimal percent;
private BigDecimal weight;
private BigDecimal price;
// constructor + getters/setters
}
I know I have to wrap a list in a Class when using POST but why is my interal data null.
Any help appreciated!
EDIT: Problem turned out to be that the request's content-type header is readonly in 'no-cors' mode and cannot be changed to application/json thus the server recognizes the received type as a plain text and not an object.
Fixed it by enabling the endpoint for cross origin requests from my front end server.

springMVC can't receive full json data

I'm trying to use $.ajax and #RequestBody, but when I use it to pass Integer type. It can't read the data and print null. What kind of data #RequestBody can receive?
Here is my code:
var user = {
"username" : "test",
"password" : "test",
"age" : 1
};
$.ajax({
url: "/test1",
type: "POST",
data: JSON.stringify(user),
contentType:"application/json; charset=utf-8",
success: function() {
alert("success")
}
})
and this is my controller:
#RequestMapping(value = "/test1")
public String test2(#RequestBody User user) {
//Can't receive the Param.
// console result : null
System.out.println(user.getAge());
//Nothing wrong
//console result:
// username: test
// password: test
System.out.println(user.getUsername());
System.out.println(user.getPassword());
return "test";
}
Here is User class:
public class User {
private Integer age;
private String username;
private String password;
//Setting and Getting
}
I found where the issue is. In User class:
public class User {
//It should be `int`
private Integer age;
}
int is a base data type. Integer is a wrapper class. I need to transform data type.

dont Post JSON array to mvc controller

I'm trying to post JSON to a mvc controller through AJAX. I use this code but it does not do the post.
$(document).ready(function(){
$(".btn-success").click(function(e){
var urData = { City: 'Moscow', Age: 25 };
$.ajax({
url: "/Category/Create/",
type: "POST",
dataType: "json",
traditional: true,
contentType : "application/json",
data: urData,
success: function(maindta) {
alert(maindta);
},
error: function(jqXHR, textStatus){
}
});
e.preventDefault(); //STOP default action
});
});
This is controller action
[HttpPost]
public virtual JsonResult Create(List<object> urData){
}
Your posting back an object with 2 properties so you need a model with those 2 properties
public class MyModel
{
public string City { get; set; }
public int Age { get; set; }
}
and the method needs to be changed to
public JsonResult Create(MyModel model)
{
.... // model will be populated with the values you sent
return Json(...);`
}
and you need to remove the following options from the ajax method
contentType : "application/json",
traditional: true,
Alternatively, you method can be
public JsonResult Create(string city, int age)
but you lose the benefits of model validation
Side note: Always use the Url.Action() method to ensure your url's are correctly generated
url: '#Url.Action("Create", "Category")',

JSON stringify nested object

I have to send data from view to controller using ajax.
Here is my class and I should send JSON appropriate to that class structure. Jackson will convert JSON to my class
public class RealEstateAgencyDTO extends BaseEntityDTO {
/** The name. */
private String name;
/** The description. */
private String description;
/** The site. */
private String site;
/** The phone number. */
private String phone;
/** The address of the office. */
private AddressDTO address;
public final String getName() {
return name;
}
public final void setName(final String newName) {
this.name = newName;
}
public final String getDescription() {
return description;
}
public final void setDescription(final String newDescription) {
this.description = newDescription;
}
public final String getSite() {
return site;
}
public final void setSite(final String newSite) {
this.site = newSite;
}
public final String getPhone() {
return phone;
}
public final void setPhone(final String newPhone) {
this.phone = newPhone;
}
public final AddressDTO getAddress() {
return address;
}
public final void setAddress(final AddressDTO newAddress) {
this.address = newAddress;
}
}
how should I use JSON.stringify() in order to get such an object that correspond my structure
I've tried to use smth like that but it doesn't work
var address = JSON.stringify({
country: $('#country').val(),
region: $('#description').val(),
postalCode: $('#postalCode').val(),
locality: $('#locality').val(),
additionalInfo: $('#additionalInfo').val()
});
var data = {
agencyName: $('#agencyName').val(),
description: $('#description').val(),
phoneNumber: $('#phoneNumber').val(),
webSite: $('#webSite').val(),
address: address
};
$.ajax({
type: "post",
url: "registerAgency",
data: JSON.stringify(data),
contentType: "application/json",
success: function(responseData, textStatus, jqXHR) {
alert("data saved")
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
})
You're over-complicating it. Don't stringify until the very end, otherwise you will end up with json inside of json, which is unlikely to be useful in any situation.
var address = {
country: $('#country').val(),
region: $('#description').val(),
postalCode: $('#postalCode').val(),
locality: $('#locality').val(),
additionalInfo: $('#additionalInfo').val()
};
var data = {
agencyName: $('#agencyName').val(),
description: $('#description').val(),
phoneNumber: $('#phoneNumber').val(),
webSite: $('#webSite').val(),
address: address
};
$.ajax({
type: "post",
url: "registerAgency",
data: JSON.stringify(data),
contentType: "application/json",
success: function(responseData, textStatus, jqXHR) {
alert("data saved")
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
});
the address member on object data is already stringified. The subsequent call will treat this as a string value (which it is!) JSON.stringify() will handle nested objects fine.

Why I can't make POST request with AngularJs

I've got problem with AngularJS and making POST request. My json creates fine, but when I POST it on my REST service I've got problem with:
WARNING: No operation matching request path "/ws/resources/Users/Add" is found, Relative Path: /Add, HTTP Method: POST, ContentType: application/json, Accept: application/json,text/plain,*/*,. Please enable FINE/TRACE log level for more details.
I really don't know why, because my GET request works fine.
Here are samples of codes
Rest Service:
#Path("/Users")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public class UserRESTResource {
#GET
#Path("/All")
public List<UserDto> getClients() {
//that works fine
}
#POST
#Path("/Add/{user}")
public void add(#PathParam("user") UserDto userDto) {
//to sth
}
}
This is how I make GET request which works:
$http.get('resources/Users/All').success(function(data) {
$scope.clients = data;
});
This is how I make json and make POST request:
$scope.Add = function() {
$http({
method: "POST",
url: "resources/Users/Add",
data: {
"user" : {
"firstName" : $scope.firstNameA,
"lastName" : $scope.lastNameA,
}
},
headers: {'Content-Type':'application/json'}
});
}
UserDto:
#XmlRootElement(name = "user")
#XmlAccessorType(XmlAccessType.FIELD)
public class UserDto {
public long id;
public String firstName;
public String lastName;
}
What I'm doing wrong?
I would guess that when you post, the user isn't in the URL so it won't match the route definition.