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"

4
  • 1
    what is var? where is it declared? Commented Jun 5, 2018 at 12:34
  • You might want to check out stackoverflow.com/questions/7672858/… Commented Jun 5, 2018 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. Commented Jun 5, 2018 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 Commented Jun 5, 2018 at 13:55

1 Answer 1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.