I am trying to PARSE Json and pull values based on input key. JSON structure is not same every time
below is sample JSON structure and JSON starts and ends with [] and some time {}
[
{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"days": {
"weekdays": "Friday",
"weekends": "Sunday",
},
"batters": {
"batter": [
{
"id": "1001",
"type": "Regular"
},
{
"id": "1002",
"type": "Chocolate"
},
]
},
"topping": [
{
"id": "5001",
"type": "None"
},
{
"id": "5002",
"type": "Glazed"
},
]
}
]
{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"days": {
"weekdays": "Friday",
"weekends": "Sunday",
},
"batters": {
"batter": [
{
"id": "1001",
"type": "Regular"
},
{
"id": "1002",
"type": "Chocolate"
},
]
},
"topping": [
{
"id": "5001",
"type": "None"
},
{
"id": "5002",
"type": "Glazed"
},
]
}
i tried below code
import org.json.simple.*;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public static void main(String[] args) throws IOException, Exception {
File InputFolder = new File(System.getProperty("user.dir") + "//Files//new.json");
JsonElementFromFile(InputFolder,"name");
}
public static void JsonElementFromFile(File FilePath, String key) throws IOException, Exception {
JSONParser parser = new JSONParser();
FileReader reader = new FileReader(FilePath);
JSONArray obj = (JSONArray) parser.parse(reader);
for (Object o : obj) {
JSONObject json = (JSONObject) o;
String jsonKeyValue = (String)json.get(key).toString();
System.out.println(key + " : " + jsonKeyValue); }
}
- above code works when JSON data start with "[" but not working if it start with "{" , irrespective of any structure I should be able to get value
- i am able to pull only value from first object keys "id","type","name","ppu" but when i pass key as "days.weekdays" it is not pulling. even if i have more arrays and objectsi should be able to pull just by passing path of key, ex: "batters.batter[0].id" or "batters.batter[1].type"**
- basically i am looking for reusable code to pull values based on keys passed, dont want to hardcode any values from JSON.
thank you
2
Answers
i found easy way for this question. using com.fasterxml.jackson , we can pull any any value from JSON ,
If you don’t want to hardcode for different JSON structure, the solution is to use JSON query library.
https://github.com/octomix/josson
Deserialize Array
Deserialize Object
Query