Android Retrofit获取子对象的子对象

时间:2014-10-09 07:03:37

标签: android json retrofit

我正在尝试获取子对象Data,它是Children的子对象,如果是Data的子对象。

我知道这听起来很混乱,但这里是完整的JSON对象: Full JSON

这是我的代码:

import java.util.List;
import retrofit.RestAdapter;
import retrofit.http.GET;
import retrofit.http.Path;

public class GitHubClient {
    private static final String API_URL = "http://www.reddit.com/r/pcmasterrace/";

    static class Data {
        String kind;
        List<Children> children;
    }

    static class Children {
        Data data;
    }

    interface Reddit {
        @GET("/hot.json?limit=1")
        List<Data> data();
    }

    public static void main() {
        // Create a very simple REST adapter which points the GitHub API endpoint.
        RestAdapter restAdapter = new RestAdapter.Builder()
                .setEndpoint(API_URL)
                .build();

        // Create an instance of our GitHub API interface.
        Reddit reddit = restAdapter.create(Reddit.class);

        // Fetch and print a list of the contributors to this library.
        List<Data> data = reddit.data();
        for (Data child : data) {
            System.out.println(child.kind);
        }
    }
}

我一直收到这个错误: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2

1 个答案:

答案 0 :(得分:2)

您的设计本身存在两个错误。

  1. 返回的JSON不是数组,而是一个对象,因此尝试存储在列表中是不正确的。
  2. 名为children的数组是一个Data对象数组,而不是Children.Data
  3. 数组

    你可以用一个类来处理这个数据只是没有点儿童类。

    static class Data {
        String kind;
        String modhash;
        Data data;
        List<Data> children;
    }
    

    接下来是在主

    中访问这些值
    public static void main(String[] args) {
        // Create a very simple REST adapter which points the GitHub API endpoint.
        RestAdapter restAdapter = new RestAdapter.Builder()
                .setEndpoint(API_URL)
                .build();
    
        // Create an instance of our GitHub API interface.
        Reddit reddit = restAdapter.create(Reddit.class);
    
        // Fetch and print a list of the contributors to this library.
        Data data = reddit.data();
        for (Data child : data.data.children) {
            System.out.println(child.kind);
    
        }
    }