1

I have a Json like the following.

{"person":[{"name":"asd","age":"22"},{"name":"asd","age":"22"}]}

but it could also be:

{"person":[{"name":"asd","age":"22"},{"name":"asd","age":"22"}],"city":["NewYork"],"student":"false"}

How can I receive it in a Spring Boot Controller?

0

3 Answers 3

4

You should use @RequestBody annotation.

@RequestMapping("/api/example")
public String example(@RequestBody String string) {
    return string;
}

Later, add some validations and business logic.

You can generate custom class with http://www.jsonschema2pojo.org/. Once generated you can expect your custom class instead of String.

For further instructions, I find this tutorial interesting.

Sign up to request clarification or add additional context in comments.

3 Comments

After I asked, I found out that it was a stupid question.Thank you for still answering this question.And thank for every click 'down vote' guys,it makes me realize that this is a bad question.
English is no my mother language.My ability to express is limited.
@NBsaw- the question just don't show the effort you did. Before asking here, I suggest reading How to Ask and minimal reproducible example - they help to ask good questions.
0

You can receive the json like below, Spring Boot will convert your json into model(For example "Comment" model below) which you defined.

@RequestMapping(value = "/create", method = RequestMethod.POST)
public ResultModel createComment(@RequestBody Comment comment) {...}

Comments

-2

1) You need to difine your rest controllers. Example

@Autowired
UserService userService;

@RequestMapping(value = "/user/", method = RequestMethod.GET)
public ResponseEntity<List<User>> listAllUsers() {
    List<User> users = userService.findAllUsers();
    if (users.isEmpty()) {
        return new ResponseEntity(HttpStatus.NOT_FOUND);
    }
    return new ResponseEntity<List<User>>(users, HttpStatus.OK);
}

2) Define your pojo: Example

public class User {

 String name;
 String age;

 public User(String name, String age) {
     this.name = name;
     this.age = age;
 }

 public String getName() {
     return name;
 }

 public String getAge() {
     return age;
 }
}

3) Define a service

@Service public class UserService {

  public List<User> findAllUsers(){
    // Those are mock data. I suggest to search for Spring-data for    interaction with DB.
     ArrayList<User> users = new ArrayList<>();
     User user = new User("name", "5");
     users.add(user);
     return users;
  }
 }

You can follow this tutorial. If you want to just send a json message to a spring boot rest controller you can use a rest client like postman.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.