如何在Java中从JSON响应中获取数组

4

我正在使用Instagram REST API,需要从JSON响应中获取图像链接。

JSON类似于以下内容:

{
    "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"
        }
    }
}

我该如何在Java中引用“images”对象?

我尝试了以下代码:

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

以及这个:

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

S是以字符串形式保存的JSON响应,如下所示:

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;
    }

但在这两种情况下,我都收到了“没有图像值”的错误。


你使用的是哪个JSON库?GSON还是Simple JSON? - Tim Biegeleisen
简单的JSON。如果我无法解决这个问题,我将尝试使用GSON。 - Plays2
1
images 嵌套在 data 中。 - copeg
哦,哇,你说得对。 - Plays2
你其实并没有告诉我们你想要提取哪个链接。那么,你想要哪一个? - Tim Biegeleisen
这是标准分辨率的URL。 - Plays2
3个回答

4

images嵌套在data中。

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

1
无法接受其他请求,需等待6分钟后再试。不过这就是答案了。谢谢伙计。 - Plays2

2
尝试这段代码:
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");

这个问题并不像你想象的那么棘手,因为要获取您想要的URL,您只需要处理JSONObject(而不是JSONObjectJSONArray)。我的代码深入JSON结构,直到找到standard_resolution JSON对象,然后提取URL。


0

无论如何,使用GSON是更好的方式。创建一个对应于您的JSON对象(POJO)的类。您可以使用此在线工具http://www.jsonschema2pojo.org。您的JSON将被转换为以下内容:

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;
}

}

现在您可以从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();

就是这样。 此外,我强烈建议与 Retrofit 一起使用它来处理 REST 请求(您可以在此处查看类似主题的回答:如何使用 ProgressDialog 显示 JSON 解析进度?)。当你要显示来自 URL 的图像时,你可以使用 Glide 或 Picasso 库以简单而又出色的方式下载它们


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接