4

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);
    }
3
  • 3
    Possible duplicate of Spring MVC - How to return simple String as JSON in Rest Controller Commented Jun 2, 2018 at 6: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? Commented Jun 2, 2018 at 7: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 Commented Jan 4, 2021 at 7:50

4 Answers 4

7

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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

ResponseEntity<User> addTopic and return user - won't compile.
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);
}

Comments

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

1 Comment

in the above solution the providerContext is the object reference of the POJO class that we have to write as JSON response to ResponseEntity

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.