Retrofit Body 返回 null

3
我正在使用Retrofit与数据库进行连接,但是GSON似乎无法解析数据。JSON已经返回,但响应体未被创建,因此我无法与数据进行交互。有什么想法吗?
我的URL增加
public interface APIPlug {
@FormUrlEncoded
@POST("repair_manager/v1/login")
Call<UserResults>Login(
        @Field("email") String email,
        @Field("password") String password
        );


}

我的Retrofit构建器

public class ApiClient {

private static APIPlug REST_CLIENT;
private static final String API_URL = "http://192.168.1.85/";

static {
    setupRestClient();
}

private ApiClient() {}

public static APIPlug get() {
    return REST_CLIENT;
}

private static void setupRestClient() {

    OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

    //Uncomment these lines below to start logging each request.


    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(HttpLoggingInterceptor.Level.BODY);
    httpClient.addInterceptor(logging);


    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(API_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .client(httpClient.build())
            .build();


    REST_CLIENT = retrofit.create(APIPlug.class);
}}

User.java

public class User {

    private Boolean error;

    private String name;

    private String email;

    private String apiKey;

    private String createdAt;



    public Boolean getError() {
        return error;
    }

    public void setError(Boolean error) {
        this.error = error;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getApiKey() {
        return apiKey;
    }

    public void setApiKey(String apiKey) {
        this.apiKey = apiKey;
    }

    public String getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(String createdAt) {
        this.createdAt = createdAt;
    }

}

使用GSON的活动

 private void getUser() {

    final String email = inputEmail.getText().toString().trim();
    final String password = inputPassword.getText().toString().trim();
Call<UserResults> call = ApiClient.get().Login(email,password);

call.enqueue(new Callback<UserResults>() {

    public void onFailure(Call<UserResults> call, Throwable t) {
        Log.d("APIPlug", "Error Occured: " + t.getMessage());

        pDialog.dismiss();
    }

public void onResponse(Call<UserResults> call, Response<UserResults> response) {
    Log.d("APIPlug", "Successfully response fetched" );

    pDialog.dismiss();

    user = response.body().results;


    Log.d("APIPlug", String.valueOf(response.body().results));

    session.setLogin(true);}});

用户结果

public class UserResults {
public List<User> results;}

OkHttp日志

08-15 21:18:32.753 13629-14006/com.example.maxwell.nfc_app D/OkHttp: Date: Mon, 15 Aug 2016 20:18:26 GMT
08-15 21:18:32.753 13629-14006/com.example.maxwell.nfc_app D/OkHttp: Server: Apache/2.4.18 (Win64) PHP/5.6.19
08-15 21:18:32.753 13629-14006/com.example.maxwell.nfc_app D/OkHttp: X-Powered-By: PHP/5.6.19
08-15 21:18:32.753 13629-14006/com.example.maxwell.nfc_app D/OkHttp: Content-Length: 148
08-15 21:18:32.753 13629-14006/com.example.maxwell.nfc_app D/OkHttp: Keep-Alive: timeout=5, max=100
08-15 21:18:32.753 13629-14006/com.example.maxwell.nfc_app D/OkHttp: Connection: Keep-Alive
08-15 21:18:32.753 13629-14006/com.example.maxwell.nfc_app D/OkHttp: Content-Type: application/json
08-15 21:18:32.753 13629-14006/com.example.maxwell.nfc_app D/OkHttp: {"error":false,"name":"Rachel Simon","email":"RachelSimon2@gmail.com","apiKey":"c5996a2076d7338987d8743effc56d58","createdAt":"2016-08-13 12:41:51"}
08-15 21:18:32.753 13629-14006/com.example.maxwell.nfc_app D/OkHttp: <-- END HTTP (148-byte body)

用户类(User class)和用户结果(UserResults)是不同的吗? - fernandospr
公共类用户结果 { 公共列表<User> 结果; } - Mugzwell
onResponse 中,你应该首先使用 response.isSuccess() 进行一个 if 语句。这个返回值是 true 吗? - fernandospr
请附上OkHttp日志和您尝试解析的JSON示例。 - Egor
@egor 这有帮助吗? - Mugzwell
显示剩余2条评论
3个回答

1
正如JaythaKing所指出的那样,您收到的是JSONObject而不是JSONArray作为响应。因此,请使用Call而不是Call。
对于刚开始使用Retrofit,我建议您阅读以下内容: 使用Retrofit消耗API 并学习JSON基础知识和解析: Android JSON解析教程

1

看起来你没有检索到User对象的列表,而只是在这种情况下检索了一个对象...这就是为什么它没有被反序列化为你的POJO。你期望的是UserResults,但你只检索到了一个单独的对象。

Call<UserResults> call = ApiClient.get().Login(email,password);

应该变成:

Call<User> call = ApiClient.get().Login(email,password);

如果期望的行为是检索一个数组,则应在服务器端处理,即使只有一个元素,也应始终发送一个数组...为了避免所有错误,我所做的就是使用这个网站创建我的POJO:http://www.jsonschema2pojo.org/

0

作为选项,您可以将响应作为Json接收,然后通过any方法解析或反序列化到您的类中。

public interface APIPlug {
@FormUrlEncoded
@POST("repair_manager/v1/login")
Call<JsonElement>Login(
        @Field("email") String email,
        @Field("password") String password
        );

请求:

call.enqueue(new Callback<JsonElement>() {
    @Override
    public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
        if(response.isSuccessful()){
            JsonElement jsonElement = response.body();
            JsonObject objectWhichYouNeed = jsonElement.getAsJsonObject();

            //use any json deserializer to convert to your class.
        }
        else{
            System.out.println(response.message());
        }
    }
    @Override
    public void onFailure(Call<JsonElement> call, Throwable t) {
        System.out.println("Failed");
    }
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接