I have a spring MVC project,in the controller i have the following method :
#RequestMapping(value = IdentityServiceURIConstants.CREATE_NEW_USER, method = RequestMethod.POST)
public #ResponseBody User createUser(#RequestBody User user) {----}
this method receives a JSON object which is supposed to represent the user object.
My problem is that the fields in the user object are not identical to those received in the JSON object.
Example: first name is First_Name in JSON and firstName in object, hence, the mapping is not working.
Do u have any idea on how to solve this problem, given that i cant edit neither the user object nor the JSONobject
You can use #JsonProperty to name your java class property to the json key name like below:
import com.fasterxml.jackson.annotation.JsonProperty;
public class User {
#JsonProperty("FIRST_NAME")
private String firstName;
#JsonProperty("LAST_NAME")
private String lastName;
// getters & Setters methods
}
and your json will be something like this:
{
"FIRST_NAME": "first name",
"SECOND_NAME": "second name"
}
You can write a DTO class.
class UserDTO{
private User user;
// use getter setter to extract data from object
}
Related
So I have passed data in ajax as:
{
“name” : “Rahul”,
“age” : “23”,
“information” : [
{
“id” : “901”,
“role” : “developer”
}
],
“salary” : “21000”,
}
For this I have created two DTO classes as
class EmployeeDTO {
#SerializedName(“name”)
private String name;
#SerializedName(“age”)
private String age;
#SerializedName(“information”)
private List<InformationDTO> informationDto;
#SerializedName(“Salary”)
private String salary;
//Their getters and setters
}
I mentioned List because I took information as an array of objects. Then I have another DTO class
class InformationDTO {
#SerializedName(“id”)
private String id;
#SerializedName(“role”)
private String role;
}
Now in my Sling Servlet I am trying to get values of information array like
String information = request.getParameter(“information”);
But I am getting null value. How can I store this array information in my DTO class Employee using InformationDTO?
How to save array of objects into DTO class using sling servlet?
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 wonder.
{
"name":"test",
"age":"123"
}
String name, String age When I get this, its values will be null.
Generally, do we create a domain or bean ? Or is there only a way to get it with a map?
No, Map is not the only way to get it. You can make a class and receive it by #RequestBody
Class
public class Something {
String name;
String age;
// getter, setter and constructor
}
Controller
#RequestMapping( method = RequestMethod.POST )
#ResponseStatus( HttpStatus.CREATED )
#ResponseBody
public Long create( #RequestBody Something something ){
.....
return someLongValue;
}
You can get detail example from here
Is is possible to exclude JsonProperties in the output of a Spring Boot Rest call based on a defined condition? (eg. the role of the user)
Example:
public class Employee{
#JsonProperty
private String name;
#JsonProperty
private String fieldForManagerOnly;
#JsonProperty
private String fieldForEmployeeOnly;
}
I want to have the fieldForManagerOnly only serialized in the JSON output when the user has the ROLE manager.
I've already tried the solution with the #JsonView (as described in Latest Jackson integration improvements in Spring) but that solution is very limited as the #JsonView is bound to one controler method and I want to have only one controller method.
I've solved the problem myself. I used the JsonView solution but instead of an annotation I select the JsonView from code.
First you need an interface for the Views.
public class JsonViews {
public interface EmployeeView {}
public interface ManagerView {}
}
Mark the fields in the Model class with the #JsonView annotations.
public class Employee{
#JsonProperty
private String name;
#JsonView(JsonViews.ManagerView.class)
private String fieldForManagerOnly;
#JsonView(JsonViews.EmployeeView.class)
private String fieldForEmployeeOnly;
}
In your controller set the JsonView to use based on the role (or some other condition):
#RequestMapping(value = "/{employeeId}", method = RequestMethod.GET)
public ResponseEntity<MappingJacksonValue> getEmployee(#PathVariable long employeeId) {
Employee employee = employeeService.getEmployee(employeeId);
MappingJacksonValue jacksonValue = new MappingJacksonValue(employeeResourceAssembler.toResource(employee));
if (getRole().equals("MANAGER")) {
jacksonValue.setSerializationView(JsonViews.ManagerView.class);
} else if (getRole().equals("EMPLOYEE")) {
jacksonValue.setSerializationView(JsonViews.EmployeeView.class);
}
return new ResponseEntity<>(jacksonValue, HttpStatus.OK);
}
Annotate the field with
#JsonInclude(JsonInclude.Include.NON_NULL)
and make sure to set the field fieldForManagerOnly to null if the current user is not a manager.
I am using jersey in Java. I want to get JSON data sent via a post request. However, I am not sure how to do this, despite my searching. I am able to receive JSON data at a path, yet I can't figure out how to parse it into java variables. I assume that I need to use jackson to do this. However, I don't understand how to pass the received JSON to jackson.
#Path("/register")
public class ResourceRegister
{
#POST
#Consumes(MediaType.APPLICATION_JSON)
public String RegisterUser(//not sure what to take in here to get the json )
{
//code to deal with the json
}
There are several ways of accepting the JSON and using it in back-end.
1. set POJO elements using JAXB APIs and use object of that POJO class to access passed parameters. this will be helpful while JSON size is large.
Example:
your service declaration would be as following
#Path("/register")
public class ResourceRegister
{
#POST
#Consumes(MediaType.APPLICATION_JSON)
public String RegisterUser(RegParams regParams)
{
//code to deal with the json
}
.....
}
and you will write a POJO like following
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
#JsonIgnoreProperties(ignoreUnknown=true)
#JsonWriteNullProperties(false)
public class RegParams implements Serializable {
#JsonProperty("userId")
private long userId;
#JsonProperty("userName")
private String userName;
..
..
}
retrive JSON as a string and use jersey APIs to work with the same.
in this case you can declare your service as following
#Path("/register")
public class ResourceRegister
{
#POST
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public String RegisterUser(#FormParam("jsonObj")String jsonString)
{
//code to deal with the json
}
.....
}
and you can process that string by using jersey APIs like following
ObjectMapper om = new ObjectMapper();
JsonNode mainNode = om.readTree(jsonString);
//access fields
mainNode.get..(as per data passed, string, int etc)
for more referance you can refer this or this
You just need to place #JsonProperty annotation to your class properties and add that class to your Resource method as paramater.
You might need #JsonIgnoreProperties annotation as well if you are not deserializing everything inside the incoming json
See below:
#POST
#Consumes(MediaType.APPLICATION_JSON)
public String registerUser(MyUser myUser)
{
//code to deal with the json
}
public class MyUser{
#JsonProperty
private String name;
#JsonProperty
private String surname;
//getters & setters & constructors if you need
}