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.

2 Answers 2

4

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

2 Comments

I am failing to get this method to work, i cannot find JSON , where do i import it from.
I figured it, So i just needed to return the parsed object
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

1 Comment

i dont think thats related to the question i have, in my case i just want to read and return the json file contents.

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.