SpringBoot Return String as JSON

227 views Asked by At

I have a method that returns a fully formatted JSON as a String, ex { type: "", List1: []...} I'm trying to return that in a way that the browser interprets it as a JSON (Firefox). I've tried specifying that it produces="text/plain" but no luck. I can't put it in a wrapper class as it's already formatted.

I tried specifying produces="text/plain" and @ResponseBody. No luck, still interpreted as text, not JSON.

edit: For my purposes, using produces=MediaType.APPLICATION_JSON_VALUE worked.

@GetMapping(value="/v1/Count", produces="text/plain"
@ResponseBody
public String getCount(@RequestParam...) {
   return "{type: "", List1: []...}";
}
4

There are 4 answers

2
Andrew On

Try using produces=MediaType.APPLICATION_JSON_VALUE. For example annotate your controller method with:

@GetMapping(value="/path", produces=MediaType.APPLICATION_JSON_VALUE)
5
Maksim Eliseev On

Try to specify the produces in the annotation @RequestMapping as application/json and it will help you. For example:

@RestController
public class TestController {

    @GetMapping(path = "/test", produces = MediaType.APPLICATION_JSON_VALUE) // equals 'produces = "application/json"'
    public ResponseEntity<String> test() {
        return ResponseEntity.ok("{}"); // put your string here
    }
}
2
unusualcoder On

You can try these things:

  1. replace produces=text/plain with produces=MediaType.APPLICATION_JSON_VALUE
  2. Use @RestController instead of @Controller, then remove @ResponseBody
0
M. Deinum On

To explicitly control the return type wrap it in an ResponseEntity and specify the content type on that.

@GetMapping(value="/v1/Count", produces="text/plain"
@ResponseBody
public ResponeEntity<String> getCount(@RequestParam...) {
   return ResponseEntity.ok()
           .contentType(MediaType.APPLICATION_JSON)
           .body("{type: "", List1: []...}");
}

This will use the actual content type you provided instead of trying to infer it from the return type of the method.