0

I want to pass a JSON to the client on request. My actual code looks something like this:

...
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.Resource;
...

@RestController
public class Controller {

    @Value("classpath:file.json")
    private Resource jsonFile;

    @GetMapping(path ="json", produces = "application/json")
    public String getJSON() {
        try (InputStream in = jsonFile.getInputStream()) {
            return IOUtils.toString(in, StandardCharsets.UTF_8.name());
        }
        catch ...
    }
}

...

jsonFile is the .json file whose content i want to send back to the user, the @Value annotation adds the classpath.

The Issue is: the Response is not only the json, but also linebreaks are encodede as \n and the entire JSON is encapsulated in quotation marks making it one big string instead of an object. As the JSON is actually a .json file i would not like to parse it into an object first.

jsonFile looks like:

{
  "thing1": [
    {
      "list1": [
        "abc"
      ],
      "subthing1": {
        "list1": [
          "aaa",
          "bbb"
        ],
        "list2": [
          "ccc"
        ],
        "list3": [
          "zzz"
        ],

      },
      "subthing2": 
      ...

Edit 1: Returning JSON object as response in Spring Boot 's answers last paragraph states "If you want to return a json serialized string then just return the string.", which red for me: "if you have a json in a string, return the string"

SchreiberLex
  • 482
  • 1
  • 4
  • 25
  • 1
    what is var? where is it declared? – pvpkiran Jun 05 '18 at 12:34
  • You might want to check out https://stackoverflow.com/questions/7672858/return-only-string-message-from-spring-mvc-3-controller – Wim Deblauwe Jun 05 '18 at 13:41
  • You are getting string since your code says that. i.e return IOUtils.toString(in, StandardCharsets.UTF_8.name()); Please explain what is var in your code. – utsav anand Jun 05 '18 at 13:41
  • sorry, didn't see what info u missed, hope this is what u asked for? Also fixed that Class annotation which falsely was ät.RequestController isneatd of correct ät.RestController – SchreiberLex Jun 05 '18 at 13:55

1 Answers1

0

Use wriper for String:

class StringRespWriper {
    private String stringResponse;
    // get/set
}

and return it on controller:

@GetMapping(path ="json", produces = "application/json")
public StringRespWriper getJSON() {
    try (InputStream in = var.getInputStream()) {
    ....
}
Eugen
  • 877
  • 6
  • 16