I have spring controller marked with RestController. If I do a POST with a Json object the properties of the model class Company are not populated, e.g. the name property is null.
If I reqeust the request body in the save() method I do get a Json string which has a name property, which means I'm sure that the json body of the POST request gets transmited.
Is there something I have to do to make spring deserialize the Json string into the company argument of the save() method?
Controller:
#RestController
#RequestMapping("/company")
public class CompanyResource {
#Resource
private CompanyService companyService;
#RequestMapping(method = RequestMethod.POST)
public Company save(Company company) {
return companyService.save (company);
}
}
Company model class:
#Entity
public class Company {
#Id
private long id;
private String name;
// public setters and getters
}
You need #RequestBody annotation:
public Company save(#RequestBody Company company) {
return companyService.save (company);
}
Related
I have a DTO class with validation annotations & in a Post API request, I have to take a List of this DTO, but the validations that I have added in the DTO aren't working.
#PostMapping("/test")
public MyTinyDto test(#Valid #RequestBody List<MyTinyDto> myDtos) {
return myDtos.get(0);
}
#Data
#AllArgsConstructor
#NoArgsConstructor
public class MyTinyDto {
#Min(value = 10,
message = "Min value of Integer is ten")
Integer x;
}
Postman Request
Add #Validated to class rest controller.
#RestController
#RequestMapping("/api")
#Validated
public class Test{
#PostMapping("/test")
public MyTinyDto test(#Valid #RequestBody List<MyTinyDto> myDtos) {
return myDtos.get(0);
}
I send json Object from AngularJS POST
(json['name']="Name";json['lastName']="LastNAme");
In Spring mvc Controller I got this message
"name=Name&lastName=LastName"
I don't know the type of this message, whether it is JSON or String and how to parse to a java object.
Create a model representating your JSON object.
public class Person{
private String name;
private String lastname;
//...Setters + Getters + default constructor
}
Then in your controller handler :
#Controller
//Mapping here
public class YourController{
#PostMapping
public void getPerson(#RequestBody Person person){
//process here
}
}
I have two controllers in my micro service both are POST and accepts Request body as JSON, one is working fine and another one's JSON input from some othet team and it is with root class name , so I need to write custom object mapper for this later controller, could you please guys help,
please find the codes below,
#RestController
#Slf4j
public class Controller2 {
#RequestMapping(value = "/some/update", method = RequestMethod.POST)
public String updateEmd(#RequestBody final UpdateEMDRequest updateEMDRequest) throws JsonProcessingException {
updateEMDRequest.getBookingReference()); // null now
return "success";
}
}
and the sample json is as follows,
{
"UpdateEMDRequest":{
"TransactionStatus":"SUCCESS",
"UniqueTransactionReference":"046060420",
"PreAuthReference":"040520420",
"BookingReference":"8PJ",
"CarrierCode":"AS",
"TransactionMode":"Batch",
"CallBackUrl":"www.test.com/op/update",
"Offers":[
{
"Offer":{
"traveler":{
"firstName":"AHONY",
"surname":"DNEN",
"EMD":[
"081820470"
]
}
}
}
]
}
}
UpdateEMDRequest,java
#JsonInclude(Include.NON_NULL)
public class UpdateEMDRequest {
#JsonProperty("UniqueTransactionReference")
private String uniqueTransactionReference;
#JsonProperty("TransactionStatus")
private String transactionStatus;
#JsonProperty("PreAuthReference")
private String preAuthReference;
#JsonProperty("BookingReference")
private String bookingReference;
#JsonProperty("CarrierCode")
private String carrierCode;
#JsonProperty("TransactionMode")
private String transactionMode;
#JsonProperty("CallBackUrl")
private String callBackUrl;
#JsonProperty("Offers")
private List<Offers> offers;
}
So this json is not parsed properly and updateEMDRequest's properties are null always.
I'm working on a jax-rs RESTful application and I have a service that is supposed to save a JSON objet into a database through JPA. The service class is something like:
#Path("/items")
#Stateless
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public class ItemsService {
#Inject
protected IItemsLogic itemsServiceLogic;
#POST
public ItemDTO create(ItemDTO item){
return itemsServiceLogic.createItem(item);
}
}
the itemsServiceLogic is just a class that transforms the DTO into another Java class declared as an entity in order to be serialized in a database through JPA.
What happens is that I'm testing the application through the google chrome browser client Postman but when I send a JSON objet into the POST method, the received DTO has no properties so the database doesn't save anything, as all the DTO's properties are null.
I'm using Glassfish 4.0 to host my application and everything with the database works fine. What could be wrong?
The DTO class would be:
#XmlRootElement
public class ItemDTO {
//Id private
Long id;
//item's description
private String description;
//item's name
private String name;
//Setters and getters
public Long getId(){
return id;
}
public String getDescription(){
return description;
}
public String getName(){
return name;
}
public void setId(Long nId){
this.id=nId;
}
public void setDescription(String nDescription){
this.description = nDescription;
}
public void setName(String nName){
this.name=nName;
}
}
And i'm sending the JSON:
{"id":1,"description":"some item","name":"item1"}
The thing is that I want to hide the null elements from a RESTFul JSON response (if it's possible).
The REST controller retrieves the information from a Mongo database and because this elements doesn't exist there I would like to ignore them when they are null.
This is my REST Controller (exposed with Jersey):
#Stateless
#TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
#Path(PropertiesRestURIConstants.PROPERTIES)
#Produces(MediaType.APPLICATION_JSON)
#RequestScoped
public class GetPropertiesController {
#EJB(mappedName = PropertiesManagerRemote.MAPPED_NAME)
PropertiesManagerRemote propertiesManager;
#GET
#Path(PropertiesRestURIConstants.PROPERTIES_ALL)
public List<PropertyEntity> getAllProperties() throws DBLayerException {
return propertiesManager.getAllProperties();
}
...
...
...
}
This is my entity:
#Document(collection = "property")
public class PropertyEntity implements GenericEntity {
#Id
private String id;
private String propertyName;
private String propertyValue;
public PropertyEntity() {
}
public PropertyEntity(String propertyName, String propertyValue) {
this.propertyName = propertyName;
this.propertyValue = propertyValue;
}
...
...
...
}
And this is the result:
[{"id":"542c00c2ff5e0ba4ea58790d","propertyName":"property1","propertyValue":null},{"id":"542c00c2ff5e0ba4ea58790e","propertyName":"property2","propertyValue":null},{"id":"542c00c2ff5e0ba4ea58790f","propertyName":"property3","propertyValue":null}]
I use Spring Data for the persistence layer. I tried with JSONIgnore annotations and similar things, but nothing works for me.
Any help will be welcome.
Thanks in advance.
Try to annotate it this way:
#JsonInclude(Include.NON_EMPTY)
public class PropertyEntity implements GenericEntity {