3

Im using retrofit to get connect with a database, but the GSON seems to not be parsing the data. The JSON is being returned but the response body is not being created, so i can not interact with the data. Any ideas?

My URL addition

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


}

My Retrofit builder

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;
    }

}

The activity to use use the 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);}});

User result

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

okhttp log

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)
Ugurcan Yildirim
  • 5,973
  • 3
  • 42
  • 73
Mugzwell
  • 31
  • 1
  • 4

3 Answers3

1

It seems like you are not retrieving a list of User object but just one in this case... Thats why it's not deserialized into your POJO. You expect UserResults which is a list but you just retrieved a single object.

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

Should become :

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

Or if the expected behavior is to retrieve an array, then you should handle on the server side to always send an array even when there is just one elements... What I do to avoid all error is to create my pojo with this website : http://www.jsonschema2pojo.org/

Jaythaking
  • 2,200
  • 4
  • 25
  • 67
1

As pointed out by JaythaKing you are receiving JSONObject and not JSONArray as a response. So use Call and not Call.

For starting in Retrofit I suggest you go through this:

Consuming APIs with Retrofit

And learning JSON Basics and Parsing:

Android JSON Parsing Tutorial

Community
  • 1
  • 1
Rushi M Thakker
  • 679
  • 2
  • 15
  • 34
0

As option, you can receive your response as Json and after that parse it or deserialize by any method to your class.

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

Request:

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");
    }
});
Community
  • 1
  • 1
kkost
  • 3,640
  • 5
  • 41
  • 72