0

I have a json file that contains static data and i want to create a springboot service that returns the content of that file. Thus far i have managed to just connect to the file but im not sure how to return the json data.

This is the json:

{
"carrots": [ 1, 2, 5, 10, 12.5, 20, 50 ],
 "apple": [ 100, 500, 750, 900 ],
 "orange": [200, 500, 1000],
 "lemon": [1, 2, 5, 10, 20, 25],
 "peanuts": [200, 500, 1000]
}

This is some schedo code to what i am trying to achieve :

public JsonInformationHereAsReturnType getJsonContent() {

    File file = ResourceUtils.getFile("classpath:sample.json");

            //Read File Content
            String content = new String(Files.readAllBytes(file.toPath()));

    return content;
}

After runing the code i want to just get back the same json i.e

{
"carrots": [ 1, 2, 5, 10, 12.5, 20, 50 ],
 "apple": [ 100, 500, 750, 900 ],
 "orange": [200, 500, 1000],
 "lemon": [1, 2, 5, 10, 20, 25],
 "peanuts": [200, 500, 1000]
}

How do i achieve this result.

Erent
  • 571
  • 6
  • 15
  • 29

2 Answers2

3

You have already got the Json String in your code.If you want to get a Json Object,you just parse from it.

@Test
public void test() {
    getJson("classpath:sample.json");
}

public JSON getJson(String path) {
    File file = null;
    try {
        file = ResourceUtils.getFile(path);
        //Read File Content
        String content = new String(Files.readAllBytes(file.toPath()));
        //Get a Json String
        System.out.println(content);
        JSON json = JSON.parseObject(content);
        return json;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
Holinc
  • 641
  • 6
  • 17
0

I have found this quick and simple REST API that returns JSON as a response, you might want to take a look and pattern to this.

how to return json objects from java rest api

JekBP
  • 81
  • 4
  • i dont think thats related to the question i have, in my case i just want to read and return the json file contents. – Erent Dec 01 '18 at 05:46