【问题标题】:Expected BEGIN_OBJECT but was String at line 1 column 5预期为 BEGIN_OBJECT,但在第 1 行第 5 列是字符串
【发布时间】:2019-08-01 16:50:43
【问题描述】:

我无法从 android 应用程序将图像上传到我的服务器。我的 json 似乎是正确的。 这是我的代码。

private boolean uploadprofilePic(String user_id)
    {
        final Boolean[] imageresponse = new Boolean[1];
        if(imageadded) { //get the image
            Bitmap bitmap = ((BitmapDrawable) profileImage.getDrawable()).getBitmap();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            byte[] imageInByte = baos.toByteArray();

            //set data
            //String user_id =sharedpreferences.getString("user_id","");
            RequestBody requestFile = RequestBody.create(MediaType.parse("image/png"), imageInByte);
            MultipartBody.Part body = MultipartBody.Part.createFormData("image", "image_" + user_id + ".jpg", requestFile);
            //assert user_id != null;
            RequestBody userId = RequestBody.create(MediaType.parse("text/plain"), user_id);

            //call the api
            loginApiInterface = ApiClient.getApiClient().create(LoginApiInterface.class);

            final ProgressDialog progressDialog = ProgressDialogPopup.showProgressDialog(this,
                    getResources().getString(R.string.loading), "");
            Call<ProfilePicUploadResponse> call = loginApiInterface.uploadprofilePic(body, userId);

            imageresponse[0] = false;
            call.enqueue(new Callback<ProfilePicUploadResponse>() {
                @Override
                public void onResponse(@NonNull Call<ProfilePicUploadResponse> call, @NonNull Response<ProfilePicUploadResponse> response) {
                    //Toast.makeText(EditProfileActivity.this, "Here i m", Toast.LENGTH_SHORT).show();
                    progressDialog.dismiss();
                    //AlertPopup.alertDialogShow(EditProfileActivity.this, response.message(), "");
                    ProfilePicUploadResponse profilePicUploadResponse = response.body();
                    if (profilePicUploadResponse.getError() != null){
                        imageresponse[0] = true;
                        assert response.body() != null;
                        setResult(1);
                        finish();
                        Toast.makeText(EditProfileActivity.this, "Success", Toast.LENGTH_SHORT).show();
                    }
                    else {
                        Toast.makeText(EditProfileActivity.this, "Here i m", Toast.LENGTH_SHORT).show();
                    }

                    if (response.isSuccessful()) {
                        //Toast.makeText(EditProfileActivity.this, "it is successfull", Toast.LENGTH_SHORT).show();

                        //AlertPopup.alertDialogShow(EditProfileActivity.this, response.body().getMessage().toString(), "");
                    } else {
                        //Toast.makeText(EditProfileActivity.this, "Not success", Toast.LENGTH_SHORT).show();
                        imageresponse[0] = false;
                        AlertPopup.alertDialogShow(EditProfileActivity.this, "Some error occurred", "");
                    /*setResult(1);
                    finish();*/
                    }
                }

                @Override
                public void onFailure(@NonNull Call<ProfilePicUploadResponse> call, @NonNull Throwable t) { progressDialog.dismiss();
                    imageresponse[0] = false;
                    AlertPopup.alertDialogShow(EditProfileActivity.this, t.getMessage(), "");
                /*setResult(1);
                finish();*/
                }
            });
            return imageresponse[0];
        }
        else {
            setResult(1);
            finish();
            return imageresponse[0];
        }

    }

我有一个名为 ProfilePicUploadResponse.java 的 Pojo 类

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class ProfilePicUploadResponse {

    @SerializedName("error")
    @Expose
    private Boolean error;
    @SerializedName("message")
    @Expose
    private String message;

    public Boolean getError() {
        return error;
    }

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

    public ProfilePicUploadResponse withError(Boolean error) {
        this.error = error;
        return this;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public ProfilePicUploadResponse withMessage(String message) {
        this.message = message;
        return this;
    }
}

我也通过了 gson 来改造 builder

public class ApiClient {

    public static Retrofit retrofit=null;
    private static Gson gson = new GsonBuilder().setLenient().create();

    private static OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .connectTimeout(7, TimeUnit.MINUTES)
            .readTimeout(7, TimeUnit.MINUTES)
            .writeTimeout(7, TimeUnit.MINUTES)
            .build();

    public static Retrofit getApiClient()
    {
        if(retrofit==null)
        {
            //scalar is for text and gson for json obect and arrays
            retrofit=new Retrofit.Builder().baseUrl(base_url)
                    .client(okHttpClient)
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .build();
        }
        return  retrofit;
    }
}

每次我上传新图像时,它都会进入 OnFailure()。该调用是异步的,因为它正在调用 .enqueue 方法。

这是我的 json 响应。

{“file_name”:“CONSOLATION_Instagram.jpg”,“user_id”:“3461",“task_id”:“6875",“message”:“Your Art is uploaded successfully!“,”error”:false,“file_path”:“https:\/\/yourmasterpieces.s3.ap-south-1.amazonaws.com\/media\/artworks\/v3\/image_3461_6875.jpg”}

请帮忙。

【问题讨论】:

    标签: android json retrofit


    【解决方案1】:
    {“file_name”:“CONSOLATION_Instagram.jpg”,“user_id”:“3461",“task_id”:“6875",“message”:“Your Art is uploaded successfully!“,”error”:false,“file_path”:“https:\/\/yourmasterpieces.s3.ap-south-1.amazonaws.com\/media\/artworks\/v3\/image_3461_6875.jpg”}
    

    您的 json 响应中的第 1 行第 5 列是 ”error”:false。

    您正在尝试使用盒装数据类型(即布尔值)而不是使用解析期间不支持的原始数据类型(布尔值)。

    所以在你的响应类中,使用boolean 而不是Boolean。

    public class ProfilePicUploadResponse {
    
        @SerializedName("error")
        @Expose
        private boolean error;
        @SerializedName("message")
        @Expose
        private String message;
    
        ....
    

    【讨论】:

    • 嗨@Sagar 我已将数据类型更改为布尔值,但仍然会进入 OnFailure。但是当我将 MultipartBody.Part 变量更改为 MultipartBody.Part body = MultipartBody.Part.create(requestFile);然后它进入 OnResponse 而不是 OnFailure 但它不更新图像。
    • 对于使用改造的图像上传,我发现了一篇不错的文章。请参考它。 androidclarified.com/android-image-upload-example
    猜你喜欢
    • 2023-03-08
    • 2016-07-05
    • 2015-04-09
    • 2021-11-17
    • 1970-01-01
    相关资源
    最近更新 更多