简体   繁体   中英

How can I somehow “store” a json file in a Spring-Boot program so my web app then reads this json

Basically, I'm writing my first Spring-Boot program, and I have to get a list of products stored on a JSON file to display each product using VueJS (I know how to use Vue, I just need to get the JSON data somewhere in the webpage or smth)

I spent last 3'5 hours looking at tutorials about consuming JSON's and POST stuff and none helped.

Lets call your file config.json.

In a typical maven project, keep your file at

src/main/resources/config.json

In your code, read it like

    try {

        ClassPathResource configFile = new ClassPathResource("config.json");

        String json = IOUtils.toString(configFile.getInputStream(), Charset.forName(Util.UTF_8));
    } catch (IOException e) {
        String errMsg = "unexpected error while reading config file";
        logger.error(errMsg, e);
        throw new Exception(e);
    }

After this, use Jackson or GSON to read the json into an object. From there you can either reference it directly as a static attribute or as an attribute in component as per your use case.

Hope this code will work for you

public class JsonReader{
    public static void readFromJson() throws Exception {
        InputStream inStream = JsonReader.class.getResourceAsStream("/" + "your_config_file.json");
        Map<String, String> keyValueMap =
                new ObjectMapper().readValue(inStream, new TypeReference<Map<String, String>>() {});
        inStream.close();
    }
}

You might need to add the maven dependency for ObjectMapper()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM