简体   繁体   中英

How to grab array from json response in java

I'm working with the instagram REST api and i need to grab the image link from the JSON response.

The JSON looks similar to this:

{
    "meta":
    {
        "code": 200
    },
    "data":
    {
        "attribution": null,
        "tags":
        [
            "tag"
        ],
        "type": "image",
        "location": null,
        "comments":
        {
            "count": 7
        },
        "filter": "Normal",
        "created_time": "1451066377",
        "link": "https://www.instagram.com/p/at3rg7uj_9/",
        "likes":
        {
            "count": 39
        },
        "images":
        {
            "low_resolution":
            {
                "url": "https://url.jpg",
                "width": 320,
                "height": 320
            },
            "thumbnail":
            {
                "url": "https://url.jpg",
                "width": 150,
                "height": 150
            },
            "standard_resolution":
            {
                "url": "https://url.jpg?ig_cache_key=key",
                "width": 640,
                "height": 640
            }
        },
        "users_in_photo":
        [
        ],
        "caption":
        {
            "created_time": "1451066377",
            "text": "caption",
            "from":
            {
                "username": "f",
                "profile_picture": "https://profilepic.jpg",
                "id": "185333924",
                "full_name": "name"
            },
            "id": "17852020759022520"
        },
        "user_has_liked": false,
        "id": "1147950432085956322_185333924",
        "user":
        {
            "username": "",
            "profile_picture": "https://prifilepic.jpg",
            "id": "185333924",
            "full_name": "name"
        }
    }
}

How would I reference the 'images' object in java?

I tried this:

JSONObject object = (JSONObject) new JSONTokener(s).nextValue();
JSONObject images = object.getJSONObject("images");
JSONObject image = images.getJSONObject("standard_resolution");
String url = image.getString("url");

and this:

JSONObject object = (JSONObject) new JSONTokener(s).nextValue();
JSONArray images = object.getJSONArray("images");
JSONObject standardRes = images.getJSONObject(2);
String url = standardRes.getString("url");

S is the JSON response saved as a string like so:

try {
        URL url = new URL(link);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            StringBuilder stringBuilder = new StringBuilder();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line).append("\n");
            }
            bufferedReader.close();
            return stringBuilder.toString(); // s
        } finally {
            urlConnection.disconnect();
        }
    } catch (Exception e) {
        Log.e("ERROR", e.getMessage(), e);
        return null;
    }

but in both cases I receive a 'No value for images' error.

images is nested within data

JSONObject object = (JSONObject) new JSONTokener(s).nextValue();
JSONObject data = object.getJSONObject("data");
JSONObject images = data.getJSONObject("images");
...

Try this code:

JSONObject object = (JSONObject) new JSONTokener(s).nextValue();
JSONObject data = object.getJSONObject("data");
JSONObject images = object.getJSONObject("images");
JSONObject stan_res = object.getJSONObject("standard_resolution");
String url = stan_res.getString("url");

The problem was less hairy that you might have thought, because to get to the URL you want, you only had to handle JSONObject (rather than JSONObject and JSONArray ). My code dives down into the JSON structure until hitting the standard_resolution JSON object, and then it extracts the URL.

Anyway it is better way to use GSON. Create a corresponding to Your JSON object (POJO). U can use this online http://www.jsonschema2pojo.org . Your JSON will be converted like this:

public class Caption {

@SerializedName("created_time")
@Expose
private String createdTime;
@SerializedName("text")
@Expose
private String text;
@SerializedName("from")
@Expose
private From from;
@SerializedName("id")
@Expose
private String id;

/**
* 
* @return
* The createdTime
*/
public String getCreatedTime() {
return createdTime;
}

/**
* 
* @param createdTime
* The created_time
*/
public void setCreatedTime(String createdTime) {
this.createdTime = createdTime;
}

/**
* 
* @return
* The text
*/
public String getText() {
return text;
}

/**
* 
* @param text
* The text
*/
public void setText(String text) {
this.text = text;
}

/**
* 
* @return
* The from
*/
public From getFrom() {
return from;
}

/**
* 
* @param from
* The from
*/
public void setFrom(From from) {
this.from = from;
}

/**
* 
* @return
* The id
*/
public String getId() {
return id;
}

/**
* 
* @param id
* The id
*/
public void setId(String id) {
this.id = id;
}

}
-----------------------------------com.example.Comments.java-----------------------------------

package com.example;

import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

@Generated("org.jsonschema2pojo")
public class Comments {

@SerializedName("count")
@Expose
private Integer count;

/**
* 
* @return
* The count
*/
public Integer getCount() {
return count;
}

/**
* 
* @param count
* The count
*/
public void setCount(Integer count) {
this.count = count;
}

}
-----------------------------------com.example.Data.java-----------------------------------

package com.example;

import java.util.ArrayList;
import java.util.List;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

@Generated("org.jsonschema2pojo")
public class Data {

@SerializedName("attribution")
@Expose
private Object attribution;
@SerializedName("tags")
@Expose
private List<String> tags = new ArrayList<String>();
@SerializedName("type")
@Expose
private String type;
@SerializedName("location")
@Expose
private Object location;
@SerializedName("comments")
@Expose
private Comments comments;
@SerializedName("filter")
@Expose
private String filter;
@SerializedName("created_time")
@Expose
private String createdTime;
@SerializedName("link")
@Expose
private String link;
@SerializedName("likes")
@Expose
private Likes likes;
@SerializedName("images")
@Expose
private Images images;
@SerializedName("users_in_photo")
@Expose
private List<Object> usersInPhoto = new ArrayList<Object>();
@SerializedName("caption")
@Expose
private Caption caption;
@SerializedName("user_has_liked")
@Expose
private Boolean userHasLiked;
@SerializedName("id")
@Expose
private String id;
@SerializedName("user")
@Expose
private User user;

/**
* 
* @return
* The attribution
*/
public Object getAttribution() {
return attribution;
}

/**
* 
* @param attribution
* The attribution
*/
public void setAttribution(Object attribution) {
this.attribution = attribution;
}

/**
* 
* @return
* The tags
*/
public List<String> getTags() {
return tags;
}

/**
* 
* @param tags
* The tags
*/
public void setTags(List<String> tags) {
this.tags = tags;
}

/**
* 
* @return
* The type
*/
public String getType() {
return type;
}

/**
* 
* @param type
* The type
*/
public void setType(String type) {
this.type = type;
}

/**
* 
* @return
* The location
*/
public Object getLocation() {
return location;
}

/**
* 
* @param location
* The location
*/
public void setLocation(Object location) {
this.location = location;
}

/**
* 
* @return
* The comments
*/
public Comments getComments() {
return comments;
}

/**
* 
* @param comments
* The comments
*/
public void setComments(Comments comments) {
this.comments = comments;
}

/**
* 
* @return
* The filter
*/
public String getFilter() {
return filter;
}

/**
* 
* @param filter
* The filter
*/
public void setFilter(String filter) {
this.filter = filter;
}

/**
* 
* @return
* The createdTime
*/
public String getCreatedTime() {
return createdTime;
}

/**
* 
* @param createdTime
* The created_time
*/
public void setCreatedTime(String createdTime) {
this.createdTime = createdTime;
}

/**
* 
* @return
* The link
*/
public String getLink() {
return link;
}

/**
* 
* @param link
* The link
*/
public void setLink(String link) {
this.link = link;
}

/**
* 
* @return
* The likes
*/
public Likes getLikes() {
return likes;
}

/**
* 
* @param likes
* The likes
*/
public void setLikes(Likes likes) {
this.likes = likes;
}

/**
* 
* @return
* The images
*/
public Images getImages() {
return images;
}

/**
* 
* @param images
* The images
*/
public void setImages(Images images) {
this.images = images;
}

/**
* 
* @return
* The usersInPhoto
*/
public List<Object> getUsersInPhoto() {
return usersInPhoto;
}

/**
* 
* @param usersInPhoto
* The users_in_photo
*/
public void setUsersInPhoto(List<Object> usersInPhoto) {
this.usersInPhoto = usersInPhoto;
}

/**
* 
* @return
* The caption
*/
public Caption getCaption() {
return caption;
}

/**
* 
* @param caption
* The caption
*/
public void setCaption(Caption caption) {
this.caption = caption;
}

/**
* 
* @return
* The userHasLiked
*/
public Boolean getUserHasLiked() {
return userHasLiked;
}

/**
* 
* @param userHasLiked
* The user_has_liked
*/
public void setUserHasLiked(Boolean userHasLiked) {
this.userHasLiked = userHasLiked;
}

/**
* 
* @return
* The id
*/
public String getId() {
return id;
}

/**
* 
* @param id
* The id
*/
public void setId(String id) {
this.id = id;
}

/**
* 
* @return
* The user
*/
public User getUser() {
return user;
}

/**
* 
* @param user
* The user
*/
public void setUser(User user) {
this.user = user;
}

}
-----------------------------------com.example.Example.java-----------------------------------

package com.example;

import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

@Generated("org.jsonschema2pojo")
public class Example {

@SerializedName("meta")
@Expose
private Meta meta;
@SerializedName("data")
@Expose
private Data data;

/**
* 
* @return
* The meta
*/
public Meta getMeta() {
return meta;
}

/**
* 
* @param meta
* The meta
*/
public void setMeta(Meta meta) {
this.meta = meta;
}

/**
* 
* @return
* The data
*/
public Data getData() {
return data;
}

/**
* 
* @param data
* The data
*/
public void setData(Data data) {
this.data = data;
}

}
-----------------------------------com.example.From.java-----------------------------------

package com.example;

import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

@Generated("org.jsonschema2pojo")
public class From {

@SerializedName("username")
@Expose
private String username;
@SerializedName("profile_picture")
@Expose
private String profilePicture;
@SerializedName("id")
@Expose
private String id;
@SerializedName("full_name")
@Expose
private String fullName;

/**
* 
* @return
* The username
*/
public String getUsername() {
return username;
}

/**
* 
* @param username
* The username
*/
public void setUsername(String username) {
this.username = username;
}

/**
* 
* @return
* The profilePicture
*/
public String getProfilePicture() {
return profilePicture;
}

/**
* 
* @param profilePicture
* The profile_picture
*/
public void setProfilePicture(String profilePicture) {
this.profilePicture = profilePicture;
}

/**
* 
* @return
* The id
*/
public String getId() {
return id;
}

/**
* 
* @param id
* The id
*/
public void setId(String id) {
this.id = id;
}

/**
* 
* @return
* The fullName
*/
public String getFullName() {
return fullName;
}

/**
* 
* @param fullName
* The full_name
*/
public void setFullName(String fullName) {
this.fullName = fullName;
}

}
-----------------------------------com.example.Images.java-----------------------------------

package com.example;

import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

@Generated("org.jsonschema2pojo")
public class Images {

@SerializedName("low_resolution")
@Expose
private LowResolution lowResolution;
@SerializedName("thumbnail")
@Expose
private Thumbnail thumbnail;
@SerializedName("standard_resolution")
@Expose
private StandardResolution standardResolution;

/**
* 
* @return
* The lowResolution
*/
public LowResolution getLowResolution() {
return lowResolution;
}

/**
* 
* @param lowResolution
* The low_resolution
*/
public void setLowResolution(LowResolution lowResolution) {
this.lowResolution = lowResolution;
}

/**
* 
* @return
* The thumbnail
*/
public Thumbnail getThumbnail() {
return thumbnail;
}

/**
* 
* @param thumbnail
* The thumbnail
*/
public void setThumbnail(Thumbnail thumbnail) {
this.thumbnail = thumbnail;
}

/**
* 
* @return
* The standardResolution
*/
public StandardResolution getStandardResolution() {
return standardResolution;
}

/**
* 
* @param standardResolution
* The standard_resolution
*/
public void setStandardResolution(StandardResolution standardResolution) {
this.standardResolution = standardResolution;
}

}
-----------------------------------com.example.Likes.java-----------------------------------

package com.example;

import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

@Generated("org.jsonschema2pojo")
public class Likes {

@SerializedName("count")
@Expose
private Integer count;

/**
* 
* @return
* The count
*/
public Integer getCount() {
return count;
}

/**
* 
* @param count
* The count
*/
public void setCount(Integer count) {
this.count = count;
}

}
-----------------------------------com.example.LowResolution.java-----------------------------------

package com.example;

import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

@Generated("org.jsonschema2pojo")
public class LowResolution {

@SerializedName("url")
@Expose
private String url;
@SerializedName("width")
@Expose
private Integer width;
@SerializedName("height")
@Expose
private Integer height;

/**
* 
* @return
* The url
*/
public String getUrl() {
return url;
}

/**
* 
* @param url
* The url
*/
public void setUrl(String url) {
this.url = url;
}

/**
* 
* @return
* The width
*/
public Integer getWidth() {
return width;
}

/**
* 
* @param width
* The width
*/
public void setWidth(Integer width) {
this.width = width;
}

/**
* 
* @return
* The height
*/
public Integer getHeight() {
return height;
}

/**
* 
* @param height
* The height
*/
public void setHeight(Integer height) {
this.height = height;
}

}
-----------------------------------com.example.Meta.java-----------------------------------

package com.example;

import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

@Generated("org.jsonschema2pojo")
public class Meta {

@SerializedName("code")
@Expose
private Integer code;

/**
* 
* @return
* The code
*/
public Integer getCode() {
return code;
}

/**
* 
* @param code
* The code
*/
public void setCode(Integer code) {
this.code = code;
}

}
-----------------------------------com.example.StandardResolution.java-----------------------------------

package com.example;

import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

@Generated("org.jsonschema2pojo")
public class StandardResolution {

@SerializedName("url")
@Expose
private String url;
@SerializedName("width")
@Expose
private Integer width;
@SerializedName("height")
@Expose
private Integer height;

/**
* 
* @return
* The url
*/
public String getUrl() {
return url;
}

/**
* 
* @param url
* The url
*/
public void setUrl(String url) {
this.url = url;
}

/**
* 
* @return
* The width
*/
public Integer getWidth() {
return width;
}

/**
* 
* @param width
* The width
*/
public void setWidth(Integer width) {
this.width = width;
}

/**
* 
* @return
* The height
*/
public Integer getHeight() {
return height;
}

/**
* 
* @param height
* The height
*/
public void setHeight(Integer height) {
this.height = height;
}

}
-----------------------------------com.example.Thumbnail.java-----------------------------------

package com.example;

import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

@Generated("org.jsonschema2pojo")
public class Thumbnail {

@SerializedName("url")
@Expose
private String url;
@SerializedName("width")
@Expose
private Integer width;
@SerializedName("height")
@Expose
private Integer height;

/**
* 
* @return
* The url
*/
public String getUrl() {
return url;
}

/**
* 
* @param url
* The url
*/
public void setUrl(String url) {
this.url = url;
}

/**
* 
* @return
* The width
*/
public Integer getWidth() {
return width;
}

/**
* 
* @param width
* The width
*/
public void setWidth(Integer width) {
this.width = width;
}

/**
* 
* @return
* The height
*/
public Integer getHeight() {
return height;
}

/**
* 
* @param height
* The height
*/
public void setHeight(Integer height) {
this.height = height;
}

}
-----------------------------------com.example.User.java-----------------------------------

package com.example;

import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

@Generated("org.jsonschema2pojo")
public class User {

@SerializedName("username")
@Expose
private String username;
@SerializedName("profile_picture")
@Expose
private String profilePicture;
@SerializedName("id")
@Expose
private String id;
@SerializedName("full_name")
@Expose
private String fullName;

/**
* 
* @return
* The username
*/
public String getUsername() {
return username;
}

/**
* 
* @param username
* The username
*/
public void setUsername(String username) {
this.username = username;
}

/**
* 
* @return
* The profilePicture
*/
public String getProfilePicture() {
return profilePicture;
}

/**
* 
* @param profilePicture
* The profile_picture
*/
public void setProfilePicture(String profilePicture) {
this.profilePicture = profilePicture;
}

/**
* 
* @return
* The id
*/
public String getId() {
return id;
}

/**
* 
* @param id
* The id
*/
public void setId(String id) {
this.id = id;
}

/**
* 
* @return
* The fullName
*/
public String getFullName() {
return fullName;
}

/**
* 
* @param fullName
* The full_name
*/
public void setFullName(String fullName) {
this.fullName = fullName;
}

}

Now U can create your object from JSON:

    Example exampleObj = new GSON().fromJson(yourJSON, Example.class);
    Data dataObj = exampleObj.getData();
    Images imagesObj = dataObj.getImages();
    //now U can fetch any of your images
    String imageUrl = imagesObj.getThumbnail().getUrl();

That is it. Also I would strongly recomend to use it with Retrofit for REST (U can see may answer here for similar topic: How to use ProgressDialog to show JSON parsing progress? ). And when U gonna show your image (from url), U can use Glide or Picasso libs to download them in easy and awesome way

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