0

Upload error: Use JsonReader.setLenient(true) to accept malformed JSON at line 15 column 1 path $enter code here

I want to upload some image,but error: Use JsonReader.setLenient(true) to accept malformed JSON at line 15 column 1 path. I multiple reword URl and reword JavaBean,while error.

This Retrofit2 interface:

public interface ImageUpload {

@Multipart
@POST("/xxzx/a/tpsb/uploadPicture")
Call<UploadResult> uploadMultipleFiles(
        @PartMap Map<String, RequestBody> files
        );

Init Retrofit2:

public class ServiceGenerator {

private static final String API_BASE_URL= "http://114.115.139.232:8080/";
private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

private static Retrofit.Builder builder =
        new Retrofit.Builder()
        .baseUrl(API_BASE_URL)
        .addConverterFactory(GsonConverterFactory.create());

public static <S> S createService(Class<S> serviceClass){
    Retrofit retrofit = builder.client(httpClient.build()).build();
    return retrofit.create(serviceClass);
}

Call Retrofit2:

    private void uploadFiles() {
    
        if(imagesList.size()==0){
            Toast.makeText(MainActivity.this, "nothing", Toast.LENGTH_SHORT).show();
            return;
        }
        Map<String, RequestBody>files = new HashMap<>();
        final ImageUpload service = ServiceGenerator.createService(ImageUpload.class);
        for (int i = 0;i<imagesList.size();i++){
            File file = new File(imagesList.get(i).path);
            files.put("file" + i + "\"; filename=\"" + file.getName(),
                    RequestBody.create(MediaType.parse(imagesList.get(i).mimeType), file));
        }
        Call<UploadResult> call = service.uploadMultipleFiles(files);
        call.enqueue(new Callback<UploadResult>() {
            @Override
            public void onResponse(Call<UploadResult> call, Response<UploadResult> response) {
                if (response.isSuccessful()){
                    Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_SHORT).show();
                }
            }

        @Override
        public void onFailure(Call<UploadResult>call, Throwable t) {
            Log.i("wxl", "onFailure=" + t.getMessage());
            Toast.makeText(MainActivity.this,"error", Toast.LENGTH_SHORT).show();
        }
    });
}

Thie used Postman post:

{
"failureList": [],
"successNum": 1,
"failureNum": 0
}

javabean:

public class UploadResult<T> { 
    public int successNum;
    public int failureNum;
    public ArrayList<String> failureList;
    }
Community
  • 1
  • 1
BannyShi
  • 1
  • 1
  • Possible duplicate of [Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $](https://stackoverflow.com/questions/39918814/use-jsonreader-setlenienttrue-to-accept-malformed-json-at-line-1-column-1-path) – Erfan Apr 13 '19 at 09:34

3 Answers3

1

This using Postman post. However i am not sure how you uploaded the image via post man may be i dont know. But You need to log the data that is actually appearing in your android logs

Use Http Interceptor to logs:

  HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
    loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

This is because may be you are getting different data from your request from retrofit client which might be failure to serialize your data.

Rest everything seems to be OK.

note: dont use '/' in your api interface as you have already added to the base url's end

Killer
  • 56
  • 1
  • 5
0

Try this on your init Retrofit method:

private static Retrofit.Builder builder =

   Gson gson = new GsonBuilder()
   setLenient()
   .create();



    new Retrofit.Builder()
    .baseUrl(API_BASE_URL)
    .addConverterFactory(GsonConverterFactory.create(gson));
0

dependency::

  implementation 'io.reactivex.rxjava2:rxjava:2.2.3'
    implementation 'io.reactivex.rxjava2:rxandroid:2.1.0'
    implementation 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'
    implementation 'com.google.code.gson:gson:2.8.5'

api client ::

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;


public class ApiClient {

    public static final String BASE_URL = "https://graph.facebook.com/";
    private static Retrofit retrofit = null;


    public static Retrofit getClient() {
        if (retrofit==null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}

Request api :

String ENDPOINT_LOGIN = "era/user/login";
    //params
    String PARAM_USER_USERNAME = "username";
    String PARAM_USER_PASSWORD = "password";


    //sign_up_coach_data
String ENDPOINT_ALL_SIGNOUT = "user/fcm";
    String ENDPOINT_SIGN_UP = "user/create";
    String ENDPOINT_OPT = "user/verify";
   String ENDPOINT_ALL_CITIES = "cities/get";


  @FormUrlEncoded
    @POST(ENDPOINT_ALL_SIGNOUT)
    Call<BaseResponse> getSignOut(
            @Header("Authorization") String token,
            @Field(PARAM_USER_FCM) String fcm
    );

    @GET(ENDPOINT_ALL_CITIES)
    Call<GetAllCitiesResponse> ();

webservice helper::

public static Call<BaseResponse> getSignOut(String token) {


        return getRetrofit().create(RequestAPIs.class)
                .getSignOut(token, ""
                );

    }


 public static Call<GetAllCitiesResponse> getAllCities() {

        return getRetrofit().create(RequestAPIs.class)
                .getAllCities();
    }

activity api call ::

 private void getSignOut() {
        Callback<BaseResponse> categoryCallback = new Callback<BaseResponse>() {
            @Override
            public void onResponse(Call<BaseResponse> call, Response<BaseResponse> response) {
                stopProgress();
                Log.d("tag", "response :: " + response.isSuccessful());
                if (response.isSuccessful()) {
                    if (response.body().isStatus()) {
                        Log.d("tag", "response :: " + response.body().getData());
                        Helper.clearPreferences(getApplicationContext());
                        editor.clear();
                        Intent intent = new Intent(MapsActivity.this, StartActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                        startActivity(intent);
                        MapsActivity.this.finish();

                    } else {
                        PrettyDialogMessage(String.valueOf(response.body().getErrors()));
                    }
                } else {
                    PrettyDialogMessage(getString(R.string.ws_failure));
                }
            }

            @Override
            public void onFailure(Call<BaseResponse> call, Throwable t) {
                stopProgress();
                Log.d("tag", "response :: " + t.toString());
                //toast(getString(R.string.ws_failure));
            }
        };
        startProgress(false);

        WebServiceHelper.getSignOut(Helper.getStringValue(getApplicationContext(), KEY_BARER)).enqueue(categoryCallback);

    }


 private void getAllCities() {


        Callback<GetAllCitiesResponse> getAllCitiesResponseCallback = new Callback<GetAllCitiesResponse>() {
            @Override
            public void onResponse(Call<GetAllCitiesResponse> call, Response<GetAllCitiesResponse> response) {
                stopProgress();
                Log.d("tag", "response :: " + response.isSuccessful());
                if (response.isSuccessful()) {
                    if (response.body().isStatus()) {
                        Log.d("tag :: ", "response :  " + response.body().getData());

                        for (int i = 0; i < response.body().getData().get(i).getCityBoundry().getCoordinates().size(); i++) {
                            UserLatLang userLatLang = new UserLatLang(response.body().getData().get(i).getCityBoundry().getCoordinates().get(i).getLat(), response.body().getData().get(i).getCityBoundry().getCoordinates().get(i).getLng());
                            polygonData.add(new LatLng(userLatLang.getLattitude(), userLatLang.getLongitude()));
                        }

                        if (isPointInPolygon(new LatLng(userLattitude, userLongitude), polygonData)) {
                            if (polygonData != null)
                                polygonData.clear();
                            progressDialog.dismiss();
                            appPrefrence.SetUserCity(prefCity);
                            Intent intent = new Intent(LoginActivity.this, MapsActivity.class);
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                            startActivity(intent);
                            return;
                        } else {
                            if (polygonData != null)
                                polygonData.clear();
                        }
                    }
                    progressDialog.dismiss();
                    appPrefrence.SetUserCity("Jacksonville Beaches");
                    Intent intent = new Intent(LoginActivity.this, MapsActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    startActivity(intent);

                } else {
                    PrettyDialogMessage(String.valueOf(response.body().getErrors()));
                }
            }

            @Override
            public void onFailure(Call<GetAllCitiesResponse> call, Throwable t) {
                stopProgress();
                Log.d("tag", "response :: " + t.toString());
                //toast(getString(R.string.ws_failure));
            }
        };
        startProgress(false);

        WebServiceHelper.getAllCities().enqueue(getAllCitiesResponseCallback);


    }