访问Jsonarray的单个值

时间:2016-01-01 10:28:47

标签: java json

我用代码来获取Jsonarray

JSONArray preferenceobj = (JSONArray) personobj.get("preferences");

这个代码的json数组如下所示。如何获得个人评级值。

   [{
    "rating": 3,
    "documentId": "TRECCS-00674898-160",
    "tags": ["Romantic", "Seafood", "Family Friendly"]
}, {
    "rating": 2,
    "documentId": "TRECCS-00247656-160",
    "tags": ["Bar-hopping"]
}, {
    "rating": 3,
    "documentId": "TRECCS-00085961-160",
    "tags": ["Gourmet Food"]
}, {
    "rating": 4,
    "documentId": "TRECCS-00086637-160",
    "tags": ["Family Friendly", "Local Food", "Entertainment"]
}, {
    "rating": 4,
    "documentId": "TRECCS-00086308-160",
    "tags": ["Family Friendly", "Tourism"]
}, {
    "rating": 4,
    "documentId": "TRECCS-00086622-160",
    "tags": ["Healthy Food", "Romantic", "Gourmet Food"]
}, {
    "rating": 2,
    "documentId": "TRECCS-00809111-160",
    "tags": ["Wellness", "Family Friendly", "Sport"]
}, {
    "rating": 4,
    "documentId": "TRECCS-00086310-160",
    "tags": ["Family Friendly", "Sport"]
}, {
    "rating": 4,
    "documentId": "TRECCS-00340169-160",
    "tags": ["Fashion Bargains", "Live Music", "Shopping for accessories", "Family Friendly"]
}, {
    "rating": 4,
    "documentId": "TRECCS-00018110-160",
    "tags": ["Healthy Food", "Family Friendly", "Local Food", "Organic Food"]
}, {
    "rating": 2,
    "documentId": "TRECCS-00085880-160",
    "tags": ["Romantic", "Sailing", "Seafood"]
}, {
    "rating": 4,
    "documentId": "TRECCS-00259825-152",
    "tags": ["Family Friendly", "Budget Friendly"]
}]

2 个答案:

答案 0 :(得分:1)

使用此:

JSONArray preferenceobj = (JSONArray) personobj.get("preferences");
List<Integer> ratings = new ArrayList<>();

for(int i = 0; i < preferenceobj.length(); i++) {
    JSONObject obj = preferenceobj.getJSONObject(i);

    int rating = obj.getInt("rating"); // Your rating
    ratings.add(rating);
}

// Show ratings
for(Integer rating : ratings) {
    System.out.println(rating);
}

答案 1 :(得分:-1)

我使用Srarta的明确评论解决的答案是:

JSONArray preferenceobj = (JSONArray) personobj.get("preferences");
                List<Long> ratings = new ArrayList<>();

                for(int i = 0; i < preferenceobj.size(); i++) {
                    JSONObject obj1 = (JSONObject) preferenceobj.get(i);

                    Long rating = (Long)obj1.get("rating");
                    ratings.add(rating);
                }

                // Show ratings
                for(Long rating : ratings) {
                    System.out.println(rating);
                }