webentwicklung-frage-antwort-db.com.de

So erhalten Sie fehlerhaftes JSON in Retrofit 2

Ich sende eine Anfrage, erhalte aber eine Ausnahme, obwohl die Anfrage erfolgreich war (Die API, mit der ich interagiere, sendet bei Erfolg einen OTP).

Die Ausnahme ist:

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)

Wie würde ich nun das missgebildete JSON sehen? Um zu wissen, ob das Json-Objekt fehlerhaft ist, ob es sich um das zurückgegebene Objekt handelt (was ich als String erwarten kann) oder um das Objekt, das ich sende.

Verzeihen Sie mir, wenn dies eine triviale Frage ist. Ich habe erst ab dieser Woche mit der Android-Entwicklung begonnen.

Hier ist der 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;
}

Schnittstelle:

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


    }
}

und hier ist der Anruf:

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

    });
11
Renier

Protokollieren Sie einfach Ihre Netzwerkantworten, damit Sie sehen, was falsch ist.

@Override
public Response intercept(Chain chain) throws IOException {
    Response response = chain.proceed(chain.request());
    Log.w("[email protected]", response.body().string());
    return response;
}
9
dtx12

Verwenden Sie den String-Konverter für Retrofit-Restadapter

 RestAdapter adapterRfqPost = new RestAdapter.Builder()
                    .setEndpoint(Constants.ENDPOINT)
                    .setConverter(new ConstantsMethods.StringConverter())
                    .build();

Stringkonverter-Klasse

public static class StringConverter implements Converter {
        @Override
        public Object fromBody(TypedInput typedInput, Type type) throws ConversionException {
            String text = null;
            try {
                text = fromStream(typedInput.in());
            } catch (IOException ignored) {/*NOP*/ }
            return text;
        }

        @Override
        public TypedOutput toBody(Object o) {
            return null;
        }



 public static String fromStream(InputStream in) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        StringBuilder out = new StringBuilder();
        String newLine = System.getProperty("line.separator");
        String line;
        while ((line = reader.readLine()) != null) {
            out.append(line);
            out.append(newLine);`enter code here`
            }`enter code here`
            return out.toString();
        }
    }
0
amar mule