Retrofit返回空对象,但json似乎有效

时间:2015-06-21 08:14:33

标签: android gson retrofit

这是我从终端获得的json。我使用代理获得它,所以这正是改造的结果:

Connected to MySQL 
connected to db 

我像这样创建RetrofitService:

{
    "id": 1,
    "email": "jacek@gmail.com",
    "name": "Jacek KwiecieŇĄ",
    "google_plus_id": "117434793312604634191",
    "facebook_id": null,
    "avatar_url": "https://some_url",
    "last_login_at": "2015-06-14T12:36:58.831Z",
    "created_at": "2015-06-14T12:36:58.829Z",
}

最后这是我的模特课:

private static final RestAdapter REST_ADAPTER = new RestAdapter.Builder()
        .setEndpoint(BuildConfig.SERVER_URL)
        .setConverter(new GsonConverter(new GsonBuilder().create()))
        .build();

public static final Api API = REST_ADAPTER.create(Api.class);

为什么改装会给我一个空的User对象? Json是有效的,不会抛出任何错误。

1 个答案:

答案 0 :(得分:1)

给出返回JSON的模拟API:http://www.mocky.io/v2/55867bf40258d3a80360db06

这个演示工作正常:

import com.google.gson.annotations.SerializedName;
import retrofit.RestAdapter;
import retrofit.http.GET;

public class RetrofitDemo {

  static class User {

    public long id;
    public boolean active;
    public String email;
    public String name;
    @SerializedName("google_plus_id") public String googlePlusId;
    @SerializedName("facebook_id") public String facebookId;
    @SerializedName("avatar_url") public String avatarUrl;
    @SerializedName("cover_photo_url") public String coverPhotoUrl;
    @SerializedName("last_login_at") public String lastLoginAt;
    @SerializedName("created_at") public String createdAt;

    @Override
    public String toString() {
      return "User{" +
          "id=" + id +
          ", active=" + active +
          ", email='" + email + '\'' +
          ", name='" + name + '\'' +
          ", googlePlusId='" + googlePlusId + '\'' +
          ", facebookId='" + facebookId + '\'' +
          ", avatarUrl='" + avatarUrl + '\'' +
          ", coverPhotoUrl='" + coverPhotoUrl + '\'' +
          ", lastLoginAt='" + lastLoginAt + '\'' +
          ", createdAt='" + createdAt + '\'' +
          '}';
    }
  }

  interface API {

    @GET("/55867bf40258d3a80360db06")
    User getUser();
  }

  public static void main(String[] args) {

    API api = new RestAdapter.Builder()
        .setEndpoint("http://www.mocky.io/v2")
        .build()
        .create(API.class);

    System.out.println(api.getUser());
  }
}

修改

从日志中我看到您的服务器以Content-Type: application/json回复。尝试让它以特定的编码进行回复,例如:Content-Type: application/json; charset=utf-8