Reputation: 3715
I am new to implement REST using Spring. I have created an REST API which accepts the user
object for CRUD operation. The user
entity has lot of fields mapped to the table like created_time
, updated_time
and some other field which I do not expect in the POST method. I just need the username
and age
in the object. How can I get this for both accepting and sending the response object as json.
@RestController
@RequestMapping (value = "/user" , produces = {"application/json"}, consumes = {"application/json"})
public class UserController{
@Autowired
private UserService userService;
@RequestMapping(value = "/user", method = RequestMethod.POST)
public User createUser(@RequestBody User user){
User user = userService.createUser(user);
return user;
}
Expected input {username" :"Ram", age:: 33}
Expected response {id;;24, username" :"Ram", age:: 33}
Upvotes: 1
Views: 1076
Reputation: 22214
You can handle this case easily if you use Jackson for JSON de/serialization (just include it in your classpath). If Jackson doesn't find a field in JSON it will initialize the Java class field with the default value e.g. null. So when deserializing a User
from the body of a POST request, it will set username
and age
and id
will be 0 or null.
If you then want specific fields of User
to be ignored only for serialization you may annotate the corresponding getter methods with @JsonIgnore
.
If you want to ignore most fields and serialize only a few, then configure your ObjectMapper mapper
like this:
mapper.disable(MapperFeature.AUTO_DETECT_GETTERS);
and annotate specific fields with @JsonProperty
e.g.
@JsonProperty
private static String username;
Upvotes: 1
Reputation: 3735
First, If you want to create a mature REST API then you'll have to mention a unique and meaningful URL, and add the appropriate HTTP Verb to it.
It would consider to be a better REST API handler if you'll write like this:
@RestController
public class UserController{
@Autowired
private UserService userService;
@RequestMapping(value = "/user/create", method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public ResponseEntity<User> createUser(@RequestBody User user){
HttpHeaders header = new HttpHeaders();
header.add("Content-Type", "application/json");
User user = userService.createUser(user);
return new ResponseEntity<User>(user, header, HttpStatus.OK);
}
}
Upvotes: 1
Reputation: 2365
Create seperate classes for seperate domains. If you only need user id, name and age for communicating via REST, have a User
class in the REST package with only these properties. If you need a more complex object in other parts of your service have there another class representing a user.
Upvotes: 0