如何从java中的json响应中获取数组

时间:2016-07-05 17:32:08

标签: java android json

我正在使用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;
    }

但在这两种情况下,我都会收到“无图像值”错误。

3 个答案:

答案 0 :(得分:4)

images嵌套在data

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

答案 1 :(得分: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");

你可能想到的问题不那么毛茸茸,因为要获得你想要的网址,你只需要处理JSONObject(而不是JSONObjectJSONArray)。我的代码深入到JSON结构,直到命中standard_resolution JSON对象,然后它提取URL。

答案 2 :(得分:0)

无论如何,这是使用GSON的更好方法。创建与您的JSON对象(PO​​JO)对应的。你可以在线使用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();

就是这样。 此外,我强烈建议将其与REST的Retrofit一起使用(你可以看到这里可能会回答类似主题:How to use ProgressDialog to show JSON parsing progress?)。当你要显示你的图像(来自网址)时,你可以使用Glide或Picasso libs以简单而有趣的方式下载它们