第一天改造 Android

First day with retrofit Android

这是我为我的 android 项目使用 Retrofit 的第一天,代码没有显示类别名称 + id,我可以看到 retrofit 得到 json with debug(true) 所以连接使用 API 服务器正常:

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

    }
}

问题在于您的 json 反序列化。您的回调期望接收一个 categoryDetails 数组,但您的 json 是一个包含 categoryDetails 数组的对象。我建议创建一个 class 来包装该响应:

static class CategoryResult { 
        categoryDetails categoryDetails;
} 

所以您的回调将是:

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