0

I started studied web service recently with Spring and I would like to know how to parse String into JSON. My web service allow the Motus game so a player have to find a word and has 5 attempts to do it.

I would like to post the word chose by the users into the request body of the HTTP request.

@PostMapping(value = "/jouer")
public void plays(@RequestBody String name){
   users.plays(name);
}

The JSON in the body would be like this:

{
  "name": "elephant"
}

I wouldn't like to create classes to map the JSON.

0

1 Answer 1

1

I wouldn't like to create classes to map the JSON.

I would advise you to create a class anyways. But, if you want to avoid it, you could use a Map<String, String>, as shown below:

@PostMapping(value = "/jouer")
public void plays(@RequestBody Map<String, String> payload) {
    String name = payload.get("name");
}

If you go for the class approach, you would have something like:

@Data
public class GuessAttempt {
    private String name;
}
@PostMapping(value = "/jouer")
public void plays(@RequestBody GuessAttempt payload) {
    String name = payload.getName();
}

The @Data annotation is from Lombok: It generates all the boilerplate code that is normally associated with simple beans:

  • Getters for all fields;
  • Setters for all non-final fields;
  • Appropriate toString(), equals() and hashCode() methods;
  • Constructor that initializes all final fields.

If you don't use Lombok, simply implement those methods manually.

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

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.