Springboot从资源中的json文件读取,然后返回完全相同的数据而不处理数据

时间:2018-12-01 05:16:33

标签: java json spring-boot jackson

我有一个包含静态数据的json文件,我想创建一个springboot服务来返回该文件的内容。到目前为止,我已经设法连接到文件,但是我不确定如何返回json数据。

这是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]
}

这是我要实现的一些计划代码:

public JsonInformationHereAsReturnType getJsonContent() {

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

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

    return content;
}

运行代码后,我只想返回相同的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]
}
  

我如何获得此结果。

2 个答案:

答案 0 :(得分:2)

您的代码中已经包含了Json字符串。如果要获取Json对象,只需对其进行解析。

@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;
}

答案 1 :(得分:0)

我已经找到了这种快速简单的REST API,该API返回JSON作为响应,您可能希望对此进行外观和样式化。

how to return json objects from java rest api