2

I want to return JSON below.

{ "name": "jackie" }

Postman is giving me error. Stating

Unexpected 'n'

New to Spring Boot here. 1 day old. Is there a proper way to do this?

   // POST method here
    @RequestMapping(method = RequestMethod.POST , produces = "application/json")
    ResponseEntity<?> addTopic(@RequestBody Topic topic) {

        if (Util.save(topicRepository, new Topic(topic.getTopicName(), topic.getQuestionCount())) != null) {
            return Util.createResponseEntity("Name : jackie", HttpStatus.CREATED);
        }
        return Util.createResponseEntity("Error creating resource", HttpStatus.BAD_REQUEST);
    }
Vy Do
  • 46,709
  • 59
  • 215
  • 313
sussie
  • 29
  • 1
  • 1
  • 5
  • 3
    Possible duplicate of [Spring MVC - How to return simple String as JSON in Rest Controller](https://stackoverflow.com/questions/30895286/spring-mvc-how-to-return-simple-string-as-json-in-rest-controller) – luk2302 Jun 02 '18 at 06:51
  • 2
    What on earth is `Util`? It scares me... Why would a class save things to repos and create response entities; in what version of the world are they within the same responsibility set? – Boris the Spider Jun 02 '18 at 07:38
  • The only sane way that this happens is if Util was an inner class of the controller taking care of calling services so the controller can focus on messing with input/output – T Tse Jan 04 '21 at 07:50

4 Answers4

5

This is what I use:

@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Map<String, String>> hello() {
    try {
        Map<String, String> body = new HashMap<>();
        body.put("message", "Hello world");
        return new ResponseEntity<>(body, HttpStatus.OK);
    } catch (Exception e) {
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
Ashwin
  • 7,277
  • 1
  • 48
  • 70
4

Create model and store value in that model and return model from controller. Check Below code.

class User{
     private String name;
     //getter and setter
}


 @RequestMapping(method = RequestMethod.POST , produces = "application/json")
    ResponseEntity<User> addTopic(@RequestBody Topic topic) {
          User user=new User();
          user.setName("myname");
           HttpHeaders httpHeaders = new HttpHeaders();
          return new ResponseEntity<User>(user, httpHeaders, HttpStatus.CREATED);   
    }
Sanjay
  • 2,481
  • 1
  • 13
  • 28
1

Try wrapping your response in object.

class Response implements Serializable {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

And Controller can be like this:

@RequestMapping(method = RequestMethod.POST , produces = "application/json")
ResponseEntity<?> addTopic(@RequestBody Topic topic) {

    if (Util.save(topicRepository, new Topic(topic.getTopicName(), topic.getQuestionCount())) != null) {
        Response response = new Response();
        response.setName("jackie");
        return new ResponseEntity<>(response, HttpStatus.CREATED);
    }
    return Util.createResponseEntity("Error creating resource", HttpStatus.BAD_REQUEST);
}
abstractKarshit
  • 1,355
  • 2
  • 16
  • 34
0
@PostMapping("/register/service/provider")
public ResponseEntity<?> registerServiceProvider(@RequestBody ServiceProviderRequestPayload providerContext) {

    try {
        if (providerContext == null)
            throw new BadRequestException("the request body can not be null or empty.");

        if (!providerContext.isValid())
            throw new BadRequestException("The request body doesn't seems to be valid");


        return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(new ObjectMapper().writeValueAsString(providerContext));
    } catch (BadRequestException | IllegalArgumentException e) {
        return ResponseEntity.badRequest().header("message", e.getMessage())
                .contentType(MediaType.APPLICATION_JSON).build();
    } catch (DuplicateKeyException keyException) {
        return ResponseEntity.badRequest().header("message", "There seems to be farmer config" + keyException.getCause())
                .contentType(MediaType.APPLICATION_JSON).build();
    } catch (JsonProcessingException e) {
        throw new RuntimeException(e);
    }
}
GuniorG
  • 9
  • 2
  • in the above solution the providerContext is the object reference of the POJO class that we have to write as JSON response to ResponseEntity – GuniorG Jan 04 '23 at 21:17