Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get malformed JSON in Retrofit 2

I am sending a request, but I am getting an exception, even though the request is successful(The API I am interacting with, sends an OTP on success).

The exception is:

com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 2 path $
            at com.google.gson.stream.JsonReader.syntaxError(JsonReader.java:1573)
            at com.google.gson.stream.JsonReader.checkLenient(JsonReader.java:1423)
            at com.google.gson.stream.JsonReader.doPeek(JsonReader.java:575)
            at com.google.gson.stream.JsonReader.peek(JsonReader.java:429)
            at com.google.gson.internal.bind.TypeAdapters$13.read(TypeAdapters.java:349)
            at com.google.gson.internal.bind.TypeAdapters$13.read(TypeAdapters.java:346)
            at com.google.gson.TypeAdapter.fromJson(TypeAdapter.java:256)
            at retrofit.GsonConverter.fromBody(GsonConverter.java:42)
            at retrofit.OkHttpCall.parseResponse(OkHttpCall.java:144)
            at retrofit.OkHttpCall.access$000(OkHttpCall.java:25)
            at retrofit.OkHttpCall$1.onResponse(OkHttpCall.java:90)
            at com.squareup.okhttp.Call$AsyncCall.execute(Call.java:168)
            at com.squareup.okhttp.internal.NamedRunnable.run(NamedRunnable.java:33)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
            at java.lang.Thread.run(Thread.java:856)

Now how would I see that malformed JSON? In order to know if what Json object is malformed, if it is the object being returned(which I am expecting to be a string) , or is it the object That I am sending.

Forgive me if this is a trivial question, I only started with Android development, as of this week.

Here is the service:

public static EnrollmentApiInterface getApiClient(){
    if (EnrollmentRequest == null) {
        OkHttpClient client = new OkHttpClient();
        client.interceptors().add(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Response response = chain.proceed(chain.request());

                Request request = chain.request();
                Buffer buffer = new Buffer();
                request.body().writeTo(buffer);
                String body = buffer.readUtf8();
                Log.println(10, TAG, body);
                Log.i(TAG, "hello:        " + response);

                String bodyString = response.body().string();
                Log.i(TAG, bodyString);
                response = response.newBuilder()
                    .body(ResponseBody.create(response.body().contentType(), bodyString))
                    .build();
                return response;
            }
        });

        Gson gson = new GsonBuilder()
            .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
            .create();

        Retrofit retrofit = new Retrofit.Builder()
            // .baseUrl("http://10.0.2.2:6543/") // On AVD
            .baseUrl("http://192.168.0.106:6543") // On device
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build();

        EnrollmentRequest = retrofit.create(EnrollmentApiInterface.class);
    }
    return EnrollmentRequest;
}

Interface:

public interface EnrollmentApiInterface {

        @Headers({
            "Accept: application/json",
            "Content-Type: application/json"
        })
        @POST("auth/enroll")
        Call<String> RequestEnrollment(@Body JsonObject EnrollmentDetails);

        @Headers({
            "Accept: application/json",
            "Content-Type: application/json"
        })
        @POST("auth/enroll/auth")
        Call<String> AuthoriseEnrollment(@Body JsonObject LoginDetails);


    }
}

and here is the call:

EnrollmentRequest request = new EnrollmentRequest();
    request.setMsisdn(MsisdnTxt.getText().toString());
    request.setId_number(IdNumberTxt.getText().toString());
    EnrollmentApiClient.EnrollmentApiInterface service = EnrollmentApiClient.getApiClient();
    Log.i(TAG, "REQUEST:   " + request.toJson());
    Call<String> call = service.RequestEnrollment(request.toJson());
    call.enqueue(new Callback<String>() {
        @Override
        public void onResponse(Response<String> response) {
            Log.i(TAG, "ON RESPONSE" + response);
            Log.i(TAG, "ON RESPONSE BODY" + response.body());
            // Create object of SharedPreferences.
            SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(that);
            //now get Editor
            SharedPreferences.Editor editor = sharedPref.edit();
            //put your value
            editor.putString("IDnumber", IdNumberTxt.getText().toString());
            editor.putString("Msisdn", MsisdnTxt.getText().toString());

            //commits your edits
            editor.commit();
            Log.i(TAG, "onClick-AFTER");
            Intent intent = new Intent(getApplicationContext(), AuthoriseActivity.class);
            startActivity(intent);

        }

        @Override
        public void onFailure(Throwable t) {
            // It always comes in here
            Log.i(TAG, "NOTHERE", t);
            Log.d("CallBack", " Throwable is " + t.toString());

            Toast.makeText(EnrollActivity.this, "Request Failed", Toast.LENGTH_LONG).show();
        }

    });
like image 737
Renier Avatar asked Sep 30 '15 08:09

Renier


1 Answers

Just log your network responses, so you will see what's wrong.

@Override
public Response intercept(Chain chain) throws IOException {
    Response response = chain.proceed(chain.request());
    Log.w("Retrofit@Response", response.body().string());
    return response;
}
like image 141
dtx12 Avatar answered Sep 27 '22 22:09

dtx12