简体   繁体   中英

Read JSON Object from an Array using Simple JSON Jar

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);
        }
    }   
}
String itemId;
for (int i = 0; i < itemList.length(); i++) {
        JSONObject obj= itemList.getJSONObject(i);
        itemId=(String) jsonObject.get("ItemId");
}

Try the above instead of iterator. Note: if you're using(importing) org.json.simple.JSONArray, you have to use JSONArray.size() to get the data you want. But use JSONArray.length() if you're using org.json.JSONArray.

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