I have a JSON file that contains nested key-value pairs. My JSON file looks like this
{
"TagName1":{
"TestCaseName1":{
"Status":"pass",
"RunTime":"063045"
},
"TestCaseName2":{
"Status":"fail",
"RunTime":"064045"
}
},
"TagName2":{
"TestCaseName3":{
"Status":"pass",
"RunTime":"073045"
},
"TestCaseName4":{
"Status":"fail",
"RunTime":"074045"
}
}
}
I want to fetch the name of test cases based on their Status
. Is there a way to do fetch nested key-values from JSON file?
I tried to solve this problem by using Reader and creating nested Hashmap of key-value pair, something like this
try{
Gson gson = new Gson();
Reader reader = Files.newBufferReader(Paths.get(filePath));
HashMap<String, HashMap<String, HashMap<String,String>>> parsedJson = gson.fromJson(reader,HashMap.class);
}
I am struck at extracting the Status value. Is there a way to read the Status
value and fetch the name of test case.
4
Answers
With the gson library it could be achived like this:
You can use JSONObjects to parse the document
@gdomo ‘s answer is pretty clean, here is how you can do the same with jackson
notice I am using a defined TestCase class "which is cleaner practice"
You may try library Josson.
https://github.com/octomix/josson
Output