2015-11-12 36 views
0

這是我的第一天使用改造爲我的android projet和代碼沒有顯示categoryname + id,我可以看到改造得到與調試(真)的JSON所以與API服務器的連接是OK:改造的第一天Android

我的JSON是:

{ 
    categoryDetails: [{ 
     id: "33", 
     categoryName: "Automotive" 
    }, { 
     id: "20", 
     categoryName: "Baby & kids" 
    }, { 
     id: "21", 
     categoryName: "Books & Media" 
    }, { 
     id: "12", 
     categoryName: "Computers & Accessories" 
    }, { 
     id: "7", 
     categoryName: "Electronics" 
    }, { 
     id: "24", 
     categoryName: "Food" 
    }] 
    } 

和Java代碼:

package org.goodev.retrofitdemo; 
import java.util.List; 
import android.util.Log; 
import retrofit.Callback; 
import retrofit.RestAdapter; 
import retrofit.http.GET; 
import retrofit.http.Path; 

public class GitHubClient { 

    private static final String API_URL = "http://192.168.1.13"; 
    private static final String TAG = null; 

    static class categoryDetails { 
     String id; 
     int categoryName; 

     @Override 
     public String toString() { 
      return id + ", " + categoryName; 
     } 

    } 

    interface Category { 

     @GET("/seller/category") 
     void contributors(Callback<List<categoryDetails>> callback); 
    } 

    public static void getContributors(Callback<List<categoryDetails>> callback) { 

     Log.e(TAG, "retrofit"); 


     // Create a very simple REST adapter which points the GitHub API 
     // endpoint. 
     RestAdapter restAdapter = new RestAdapter.Builder().setServer(API_URL).build(); 

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



     // restAdapter.setDebug(true); 

     // Fetch and print a list of the contributors to this library. 

     if(callback==null) { Log.w("retrofit", "vide"); }else { 
      Log.w("retrofit", "no vide"); 
     } 
     cat.contributors(callback); 

    } 
} 
+0

我更願意使用改裝2.這裏就是例子。 https://stackoverflow.com/questions/32389584/retrofit-android-not-working-and-has-no-error/46278758#46278758 –

回答

2

問題是與您的JSON反序列化。您的回調期望收到一個categoryDetails的數組,但是您的json是一個包含categoryDetails數組的對象。我會建議創建一個類來包裝響應:

static class CategoryResult { 
     categoryDetails categoryDetails; 
} 

所以你的回調將是:

@GET("/seller/category") 
void contributors(Callback<CategoryResult> callback); 
+0

謝謝你這麼多! – Mourad