I have a JSON file as below
{
"ClassId": "1",
"ClassName": "mobiles",
"ClassItems": [
{
"ItemId": "1",
"ItemName": "Nokia",
"ItemImageName": "nokia.jpg",
"ItemUnitPrice": "200.00",
"ItemDiscountPercent": "0"
},
{
"ItemId": "2",
"ItemName": "Samsung",
"ItemImageName": "samsung.jpg",
"ItemUnitPrice": "400.00",
"ItemDiscountPercent": "0"
}
]
}
I am trying to access the ItemIds for all the items with ClassId=1. I am able to print the complete json array but I am not able to find print itemIds alone.
The java code I use is below:
public class JSONExample {
/**
* @param args the command line arguments
* @throws java.io.IOException
*/
public static void main(String[] args) throws IOException {
JSONParser parser=new JSONParser();
try {
Object obj=parser.parse(new FileReader("JSON/TestJson.json"));
JSONObject jsonObject=(JSONObject) obj;
String classId=(String) jsonObject.get("ClassId");
String className=(String) jsonObject.get("ClassName");
if(classId.equals("1")){
JSONArray itemList = (JSONArray) jsonObject.get( "ClassItems" );
Iterator iterator=itemList.iterator();
while(iterator.hasNext())
{
System.out.println(itemList.get(1));
iterator.next();
}
}
} catch (FileNotFoundException ex) {
Logger.getLogger(JSONExample.class.getName()).log(Level.SEVERE, null, ex);
} catch (ParseException ex) {
Logger.getLogger(JSONExample.class.getName()).log(Level.SEVERE, null, ex);
}
}
}