如何访问 JSON 对象中的嵌套数组 (Android)

How to access nested arrays in a JSON object (Android)

我的 JSON 的结构是,

"posts":[
    //Post 1.        
    {
        "images":{
            "small":{
                "url": "http://..."
                "width": 64
            },
            "large":{
                "url": "http://..."
                "width": 128
            }
        },

        "caption":"..."
    },

    {
        //Post 2
        "images":{
            "small":{
                "url": "http://..."
                "width": 64
            },
            "large":{
                "url": "http://..."
                "width": 128
            }
        },

        "caption":"..."

     } 
]

我想从每个 post 中获取 posts -> 图片 -> 大 -> url一个字符串。

这是我所做的:

JSONArray jsonarray = jsonobject.getJSONArray("posts");

for (int i = 0; i < jsonarray.length(); i++) {
    JSONObject jsonobject = jsonarray.getJSONObject(i);
    JSONArray innerArray1 = jsonobject.getJSONArray("images");
    JSONArray innerArray2 = innerArray1.getJSONArray(0);    //gets "large"
    JSONArray innerArray3 = innerArray2.getJSONArray(1);    //gets "url"
    String finalString = innerArray3.toString();
}

我期望 finalString 中 "url" 的值,但它最终为空。

我做错了什么?

"images"、"small"、"large" 是 JSONObjects(注意花括号),而不是 JSONArrays(方括号),您需要提取它们。

JSONArray jsonarray = jsonobject.getJSONArray("posts");

for (int i = 0; i < jsonarray.length(); i++) {
    JSONObject jsonobject = jsonarray.getJSONObject(i);
    JSONObject innerObject1 = jsonobject.getJSONObject("images");
    JSONObject innerObject2 = innerObject1.getJSONObject("large");    //gets "large"
    String finalString = innerObject2.getString("url");
}

只需使用 Retrofit 和 GSON

建几个模型类叫Posts.javaPost.javaImage.java

Posts.java

public class Posts {

   @SerializedName("posts")
   private List<Post> mPosts;
   public List<Post> getPosts() {
        return mPosts;
   }

}

Post.java

public class Post {

   @SerializedName("image")
   private Image mImage;
   public Image getImage() {
        return mImage;
   }

   @SerializedName("caption")
   public String mCaption;
   public String getCaption() {
       return mCaption;
   }

}

Image.java

public class Image {

   @SerializedName("small")
   private String mSmallImageUrl;
   public Image getSmallImageUrl() {
        return mSmallimageUrl;
   }

   @SerializedName("large")
   public String mLargeImageUrl;
   public String getLargeImageUrl() {
       return mLargeImageUrl;
   }

}

SerializedName 注释来自 GSON 库,它应该已经是您可以实现的 Android Studio 库包的一部分。

它实际上为您创建了 POJO 个对象,您只需创建模型 类。

通过改造,实现很简单,因为您可以在某个地方声明一个 RestAdapter,如下所示:

public class Client {

        public static final String API_URL = ".......";

        // Constructor which you can initialize somewhere else.
        public Client() {

                RestAdapter mAsyncRestAdapter = new RestAdapter.Builder()
                                     .setEndpoint(API_URL)
                                     .setClient(new OkClient(new OkHttpClient()))
                                     .build();

        }

        // Implement Interfaces here somewhere. 

}

然后像这样为您的 api 端点创建接口,这有助于解耦。请注意 GET 注释来自改造。 Retrofit 还允许 POST PUT DELETE 等:

public interface IPosts {

     @GET("/posts")
     void getPosts(Callback<Posts> callback);

}

请注意,Callback 是一个改造回调,在 200 OK 状态下,它将从 API 中获取 Response 并将 JSON 转换为具有 GSON 的 Posts 对象。

您可以像这样实现接口:

public void getPosts(Callback<Posts> callback) {
    IPosts posts = mAsyncRestAdapter.create(IPosts.class);
    posts.getPosts(callback);
}

只需在您应用的某处创建以下回调:

Callback<Posts> callback = new Callback<Posts>() {

    @Override
    public void onSuccess(Posts posts, Response response) {
        // Do whatever you want with posts here
        List<Post> posts = posts.getPosts(); // Get posts for example

    }

    @Override
    public void onFailure(RetrofitError error) {
        // Handle the error

    }

};

// Pass this callback to the implementation of the interface to have it actually work
mClient.getPosts(callback);

这是一种可以轻松访问嵌套 JSON 对象的方法。使用 GSON 进行改造是一种真正的乐趣。这种方法的美妙之处在于,您所要做的就是定义回调、接口和模型。从中您可以看到代码非常少且分离。