how can i receive json as body in spring controller? - json

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

Related

How to get JSON format from a Flux<String> in SpringBoot Controller?

I am learning Reactor. I use project-reactor to build a Reactor SpringBoot Demo.I have completed a lot of function and successfully GET/POST in my DEMO.
Now I meet a question, the result return from Controller is not JSON format but a Concatenated String like this: "reactortestPostTitleReactorProgramming Reactor 3.xtestbypostman".(I use POSTMAN to test my DEMO)
What I want is a JSON format like this: ["reactortestPostTitle", "ReactorProgramming Reactor 3.x", "testbypostman"]
Now I put my code:
My basic data struction BLOGPOST defined in Entity package, and using .getTitle() method could return blog title of String Type :
#Entity
#Data
#AllArgsConstructor
#NoArgsConstructor
public class BLOGPOST {
#Id
String id;
String title;
String author;
String body;
}
Model in View, in this class , I use #JsonCreator and it works:
#Value
#Builder
#AllArgsConstructor(onConstructor = #__(#JsonCreator))
public class PostContent {
#NonNull
String title;
#NonNull
String author;
#NonNull
String body;
}
Controller Code, where I meet question is:
// Get All titles list of Blogs
#GetMapping(value = "/api/blog/alltitles", produces = MediaType.APPLICATION_JSON_VALUE)
public Flux<String> getPostAllTitles() {
return service.getAllTitlesByFlux();
}
Service Class Code, I use JPA repository.findAll() method to call data from Mysql:
:
public Flux<String> getAllTitlesByFlux(){
return Flux.fromIterable(repository.findAll())
.map(post -> {return post.getTitle();});
}
So, how I can get a JSON format String List by Flux<String> getPostAllTitles()
Take a look at this answer. This is what going on in your case. You can use the provided solution there.
Easy solution: You can simply change the Flux<String> to Flux<Object>
#GetMapping("/api/blog/alltitles")
public Flux<Object> getPostAllTitles() {
return service.getAllTitlesByFlux();
}
Another solution: If you do not want to go with the above 2 approaches, then, You are looking for List<String> and based on your requirement, your return type should be Mono<List<String>>. You can take a look at this collectList method.
// Get All titles list of Blogs
#GetMapping(value = "/api/blog/alltitles")
public Mono<List<String>> getPostAllTitles() {
return service.getAllTitlesByFlux()
.take(3)
.collectList();
}

Type of data received from AngularJS POST?

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
}
}

Role base Json output in Spring Boot

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.

Post request with json string as body and add validation to it

I am trying to add string input to spring boot application. The content type is json and I am trying to add validation to it.
#RestController
#RequestMapping(value = "/entries")
public class SampleController {
#RequestMapping(method = RequestMethod.DELETE)
#ResponseStatus(value = HttpStatus.NO_CONTENT)
public void delete(#RequestBody #NotBlank(message = "{field.required}") String username) throws Exception {
//some logic
}
}
For some reasons, #Notblank annotation does not work.
Is it right way to do it.
one way to go would be creating a model/dto class and defining your #NotBlank on a String in this class. then just change your controller-code like this:
#RequestMapping(method = RequestMethod.DELETE)
#ResponseStatus(value = HttpStatus.NO_CONTENT)
public void delete(#RequestBody #Valid MyClass myClass) throws Exception {
...
}
For more insights, look here
You can't use those validations on method parameters.
You need to bind your parameter onto an object if you want validation. Then, you just have to add #Valid annotation.
See this example.

Mapping JSON to POJO not working

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
}