简体   繁体   中英

Get JSON Array into strings.

I have a webservice which returns a JSON array in this format:

[{"imageid":"3","userid":"1","imagepath":"SLDFJNDSKJFN","filterid":"1","dateadded":"2014-05-06 21:20:18.920257","public":"t"},
{"imageid":"4","userid":"1","imagepath":"dsfkjsdkfjnkjdfsn","filterid":"1","dateadded":"2014-05-06 21:43:37.642748","public":"t"}]

I need to get all the attributes seperately? How would I do this?

I know how to do it with JSONObject if there is just 1 thing being returned, but how does it work when multiple items are returned?

Thanks

try {
        JSONArray jArray = new JSONArray(jsonString);
        String s = new String();
        for (int i = 0; i < jArray.length(); i++) {
            s = jArray.getJSONObject(i).getString("imageid").toString();
            s = jArray.getJSONObject(i).getString("userid").toString();
        }
    } catch (JSONException je) {
    }

Create an Object class with all variables, create a List for this Object, add all objects in your JSONArray to the list, use the one you need.

    List<YourObject> objList = new ArrayList<YourObject>();
    JSONArray a = new JSONArray(response);
    int size = a.length();
    for (int i=0 ; i<size ; i++){
        JSONObject aa = a.getJSONObject(i);
        String id = aa.getString("imageid");
        String userid = aa.getString("userid");
        String imagepath = aa.getString("imagepath");
        String filterid = aa.getString("filterid");
        String dateadded = aa.getString("dateadded");
        String publicText = aa.getString("public");
        YourObject obj = new YourObject(id,userid,imagepath,filterid,dateadded,publicText);
        objList.add(obj);
    }

So what you are having here is some JSON objects inside a JSON array.

What you want to do is this:

JSONArray array = ...;

for (int i = 0; i < array.length(); i++) {
    JSONObject o = array.getJSONObject(i);

    // Extract whatever you want from the JSON object.
}

I hope it helped.

You can use JSONArray to parse array of JSON response.

private void parseJsonArray(String response) {
    try {
        JSONArray array = new JSONArray(response);
        for(int i=0;i<array.length();i++){
            JSONObject jsonObject = array.getJSONObject(i);
            String ImageId = jsonObject.getString("imageid"); 
            Log.v("JSON Parser", "ImageId: "+ImageId);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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