简体   繁体   中英

Parsing json file content in java

I have a json file which contains below json data.

[{"id":1025,
"key":"SVS",
"prj_name":"SVS",
"prj_scope":"PR8",
"prj_qualifier":"WW",
"date":"2016-03-29T06:00:26-0400",
"creationDate":"2013-04-12T09:03:35-0400",
"prj_lname":"SVS",
"csr":[{"key":"test_success","test_output":85.3,"org_val":"78.3%"}]}]

I want to read test_output value in java. I tried with few json-simple api. Below is the code which I wrote.

StringBuffer sbf = new StringBuffer();
FileReader fileReader = new FileReader("C:/Users/java_backups/Downloads/output.json");
BufferedReader br = new BufferedReader(fileReader);
String line="";
while ((line = br.readLine()) != null) {
    sbf.append(line);
}
System.out.println(sbf.toString());
JSONParser jsonParser = new JSONParser();
JSONArray jsonArray= (JSONArray) jsonParser.parse(sbf.toString());

size of jsonArray is one only. I do not have any clue how can I read test_output value from json string.

Using Jackson for simplicity:

public class Test {

    private static final String JSON = "[{\"id\":1025,\"key\":\"SVS\",\"prj_name\":\"SVS\",\"prj_scope\":\"PR8\",\"prj_qualifier\":\"WW\",\"date\":\"2016-03-29T06:00:26-0400\",\"creationDate\":\"2013-04-12T09:03:35-0400\",\"prj_lname\":\"SVS\",\"csr\":[{\"key\":\"test_success\",\"test_output\":85.3,\"org_val\":\"78.3%\"}]}]";

    public static void main(String[] args) throws IOException {

        ObjectMapper mapper = new ObjectMapper();
        JsonNode actualObj = mapper.readTree(JSON);
        System.out.println(actualObj.findValue("test_output"));
    }

}

Dependency:

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.7.3</version>
    </dependency>

If you only have 1 output with the given name in each JsonObject, this will do the trick. Just iterate over the JsonArray and find the value for each JsonObject. In case your array is always just 1 element, just ignore the iteration part and simply use it as I did above.

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