Home > AI > Language > Java >

read local json file to json object

Step 1: install fastjson from alibaba

<!-- json parser -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.47</version>
</dependency>

Step 2: code

public static String readLocalJSON (String fileName) throws IOException {
    File resource = new ClassPathResource(fileName).getFile();
    String text = new String(Files.readAllBytes(resource.toPath()));
    return text;
}


public static void main(String[] args) {
    SpringApplication.run(PteApplication.class, args);
    try {
        String jsonStr = readLocalJSON("asq/asq-1.json");
        JSONObject jsonObj = JSON.parseObject(jsonStr);
        System.out.println(jsonObj.get("title"));
        System.out.println(jsonObj.get("content"));
        System.out.println(jsonObj.get("audioPath"));
    } catch (IOException e) {
        System.out.println("Wrong with reading asq/asq-1.json");
    }
}

Leave a Reply