springMVC can't receive full json data - json

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.

Related

Invalid JSON Primitive When Passing With Ajax

I'm trying to create a json object and pass it as a parameter using Ajax. Here's the js
var model = {
"Name": "test",
"Location": "Place",
"Interests": ["Code", "Coffee"]
};
$.ajax({
type: "POST",
url: "/CT01211/test",
contentType: "application/json'",
dataType: "json",
data: {
message: model
}
});
Here's the c#:
public class ModelTest
{
public string Name { set; get; }
public string Location { set; get; }
System.Collections.Generic.List<string> Interests { set; get; }
}
[HttpPost]
public ActionResult test (ModelTest message)
{
return Json(message);
}
Everything time I try I get the error: "Invalid JSON primitive".
I've tried JSON.stringify(model)
I've tried single quotes instead of double when building the model variable
I've tried changing the contentType and dataType
I've tried not having quotes around the properties:
var model = {
Name: "test",
Location: "Place",
Interests: ["Code", "Coffee"]
};
No matter what, I get the error.
Little help?

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.

How to send JSON date fields to web core API?

I have this AJAX request;
addDataToDatabase = function (callback, errorCallback, url, data) {
$.ajax({
async: true,
url: url,
contentType: "application/json",
dataType: "text",
data: data,
type: "POST"
})
.done(function (data) {
callback(data);
})
.fail(function (data) {
errorCallback(data);
});
which sends data to the web core API;
data "{\"InspectionId\":\"4471\",\"DateOfVisit\":\"25/09/2017
00:00:00\",\"NoAccessId\":\"2\",\"NoAccessComment\":\"lkjh
lkjhlkjhlkhjlkjhlklkjh lkh lkh kjh dsf\"}"
Which is pick up with this method
[HttpPost("addNoAccess")]
public async Task<IActionResult> AddNoAccessVisit([FromBody] InspectionVisitNoAccessDto noAccessVisit)
The definition of the dto is
public class InspectionVisitNoAccessDto
{
public int InspectionId { get; set; }
public DateTime DateOfVisit { get; set; }
public int NoAccessId { get; set; }
public string NoAccessComment { get; set; }
public override string ToString()
{
return $"No Access Inspection Visit, date of visit {DateOfVisit.ToLongDateString()}, id = {NoAccessId}, comment = {NoAccessComment}";
}
}
The DateOfVisit field is a date field. With the this definition, the input string for the date field does not appear to be converted from a string to a date field, as the whole object is null.
But if I change the definition from DateTime to string, everything is fine.
But I would prefer to keep the definition as it is. Is there something with the JSON input I can do to fix this?
instead of sending the date in format 25/09/2017 00:00:00, try to send it in ISO8601 format.
Example:
var d = new Date();
var n = d.toISOString();
// result
2017-09-29T14:15:39.409Z
Example is taken from w3schools.com

how to send cascade data from json to spring controller

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.

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")',