【问题标题】:How to access nested arrays in a JSON object (Android)如何访问 JSON 对象中的嵌套数组(Android)
【发布时间】:2015-08-13 16:34:12
【问题描述】:

我的 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":"..."

     } 
]

我想以字符串的形式从每个帖子中获取 posts -> images -> large -> 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”的值,但它最终为空。

我做错了什么?

【问题讨论】:

    标签: android arrays json object nested


    【解决方案1】:

    “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");
    }
    

    【讨论】:

      【解决方案2】:

      只需使用 Retrofit 和 GSON

      构建几个模型类,称为Posts.java Post.java Image.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 注释来自改造。改造还允许POSTPUTDELETE等:

      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 进行改造是一种真正的乐趣。这种方法的美妙之处在于您所要做的就是定义回调、接口和模型。从中您可以看到代码非常少且解耦。

      【讨论】:

      • 虽然我现在实现了Bidhan的方法,但还是谢谢你把我介绍给GSON。以后一定会派上用场的!
      • 别担心,如果你最终使用这种方法,请告诉我它是怎么回事
      • 另外更美的是使用这个网站自动将json字符串转换为pojo:jsonschema2pojo.org
      猜你喜欢
      • 2017-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-26
      • 2018-04-05
      • 2018-08-28
      • 1970-01-01
      • 2016-03-04
      相关资源
      最近更新 更多