2017-08-12 25 views
-1

我想分析Json這種格式:如何使用Java獲得instagram追隨者列表?

{"data": { 
    "user": { 
    "edge_follow": { 
     "count": 2554, "page_info": { 
     "node": { 
      "id": "5719761315", "username": "disneyangell" ... 
     "node": { 
      "id": "2260368333", "username": "moosa_sedaghat",... 
     "node": { 
      "id": "3982701506", "username": "alidadashi512", ... 
     . 
     . 
     . 

從這個link; 我得到了我pojo從www.jsonschema2pojo.org/ 的I試圖GsonConverter和傑克遜ObjectMapper

問題解析對象的節點列表是空的,或者它始終爲零。 如何解決這個問題? 如果我需要使用CustomConverter寫這個案例。

回答

1

所以得到你想要的,你必須到instagiam要記錄的JSON。否則,您將在獲取請求返回的JSON中獲得一個空的「邊緣」對象。如果您在此處記錄是一個例子與GSON做到這一點:

的POJO(也許你需要添加getter方法你感興趣的領域):

public class FollowJson{ 
    Data data; 
    String status; 

    public ArrayList<FollowNode> getFollowNodes(){ 
     return data.getFollowNodes(); 
    } 

    class Data{ 
     User user; 

     public ArrayList<FollowNode> getFollowNodes(){ 
      return user.getFollowNodes(); 
     } 
    } 

    class User{ 
     EdgeFollow edge_follow; 

     public ArrayList<FollowNode> getFollowNodes(){ 
      return edge_follow.getFollowNodes(); 
     } 

    } 

    class EdgeFollow{ 
     Integer count; 
     ArrayList<OuterNode> edges; 
     HashMap<String, Object> page_info; 

     public ArrayList<FollowNode> getFollowNodes(){ 
      ArrayList<FollowNode> bufList = new ArrayList<FollowNode>(); 
      for(OuterNode outer : edges){ 
       bufList.add(outer.getNode()); 
      } 
      return bufList; 
     } 

    } 

    class OuterNode{ 
     FollowNode node; 

     public FollowNode getNode(){ 
      return node; 
     } 

    } 

    class FollowNode { 
     Boolean followed_by_viewer; 
     String full_name; 
     String id; 
     Boolean is_verified; 
     String profile_pic_url; 
     Boolean requested_by_viewer; 
     String username; 

     public Boolean getFollowedStatus(){ 
      return followed_by_user; 
     } 

     public String getId(){ 
      return id; 
     } 

     public String getUsername(){ 
      return username; 
     } 
    } 

} 

然後通過POJO.class和JSON字符串到方法:

public <T> T getJsonFromString(String jsonString, Class<T> var){ 
    GsonBuilder builder = new GsonBuilder(); 
    return builder.create().fromJson(jsonString, var); 
} 

可以再調用getFollowNodes()返回的對象,它返回對象的表示在JSON的「節點」的陣列(FollowNode)上。

+0

感謝我沒有檢查響應主體。但現在如何使用okhttp獲取該json?我的意思是如何設置cookie或... – Mehrad

+0

我從來沒有與okhttp一起工作,但一般來說,你可以使用java.net.CookieManager來處理cookie。您從響應頭中獲取cookie,例如通過向https://www.instagram.com/accounts/login/發送獲取請求。然後,您發送一個發佈請求到上面的鏈接與cookie,參數(用戶名和密碼)和必要的請求標題。您可以使用瀏覽器的開發人員工具來檢查帖子標題包含的內容(如:「主機」,「csrftoken」,...)。 – TheDude

+0

我在瀏覽器的Http頭中找到了cookie,它正在工作......再次感謝:) – Mehrad

相關問題