2014-10-09 61 views
0

我試圖獲取子對象Data,它是子對象Children,如果子對象爲DataAndroid Retrofit獲取子對象的子對象

我知道這聽起來讓人有些困惑,但這裏是完整的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

回答

2

有是你設計本身的兩個錯誤。

  1. 返回的JSON不是一個數組,而是一個試圖存儲在列表中的對象是不正確的。
  2. 稱爲子陣列是數據對象數組不Children.Data

的數組,你可以用一個類只有數據沒有一點生兒育女類的處理這個問題。

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

    } 
} 
+0

那麼訪問這些值,也更容易! 但我無法弄清楚如何從'children'''data'對象中獲得'title'元素 – dasmikko 2014-10-09 12:51:17

+0

在循環中使用'System.out.println(child.data.kind)' – 2014-10-10 05:16:02