当前位置: 首页 > 知识库问答 >
问题:

应为BEGIN_对象,但在第1行第1列路径处为字符串-Laravel改装2

百里杰
2023-03-14

我使用Laravel构建了一个简单的API,它运行良好。我的Android应用程序应该使用这个API中的数据,但对于一些JSON响应,我得到了一个错误

应为BEGIN_对象,但在第1行第1列路径处为字符串

在得到这个错误之前,错误如下:

使用JsonReader。setLenient(true)在第1行第1列路径接受格式错误的JSON

然后我setLenient(true)来解决它。

我在许多其他帖子中看到,这个问题是一个畸形的JSON,但它似乎都很好。

给出错误的JSON响应:

{
    "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6ImRhMWUxNzU4YmI1YTFjMjAzZDI1MDk5OTM4YTljMjgwNDUyMjYzMDFhNjZiZmViZmJlMTQyY2FmNGU4OGUwMzc2NTZkN2RmZjI4NDUxMTEzIn0.eyJhdWQiOiIxIiwianRpIjoiZGExZTE3NThiYjVhMWMyMDNkMjUwOTk5MzhhOWMyODA0NTIyNjMwMWE2NmJmZWJmYmUxNDJjYWY0ZTg4ZTAzNzY1NmQ3ZGZmMjg0NTExMTMiLCJpYXQiOjE1NTE3OTIzMzAsIm5iZiI6MTU1MTc5MjMzMCwiZXhwIjoxNTgzNDE0NzMwLCJzdWIiOiIxIiwic2NvcGVzIjpbXX0.bi4l9mpUDLoYMLWwd1JyCAfoN2GtwpnpEmGnzsoDoIP_rcTWfT9IsixX4iwtbjSdOTBFkqSD9oGz8KncI24spgnKhofZelClSP6tNtI6P8q2b_PmnefytmNfu_fWBAvSTD2Tia8-cMCu_eF9QfNoOv_9JCYAaY__DY2W_zI3u8uLv25EZQPgBiW7MIT_gm9ZnD6JJlCL4rkgUuhdDG8lkjHCryAYVBqXsGLizl6YdgBp8zMYzONzjxT4nhTARL_aywE9ejZCt5Mkh5qvoGms4zkMMAW0OIYVP_puB7MSPJAriCR1kaBO06MSNGcfAdorn5VDpfwFV8t25mftOeaM1x8IvWT1K0_Hi0BtdV2twtJ-_uHcmIn8QiF3Tc6On7YWWWGEfJw0vAGqK5RaYtWVSo5iWbAiD5rsmCQRQDsg4GnEH9AnYHjcjortBe01YuimQ4TMSIgWLpRfExwcPgQkonklWqODcE8nvuWzyKUirmm56gGj1wBZciqrYsDRTImP4Ntv1Q5Tb3r2PoFlqxfn3_qux1OQpTyzHGEOEaE9ZQnNoELjwGd5nUuFOYCOdwafIUsG0atHtoPBj_S6jTsJJdIWqQzCexchpkwBUgP5i6o1QCai7BcOnTXKJ3V6kV17SGtiP7gqTM9fvESD0BIuK4Xd0dsA8mc67_HwLJyhpXM",
    "token_type": "Bearer",
    "expires_at": "2019-03-19"
}

工作JSON响应:

{
    "message": "The given data was invalid.",
    "errors": {
        "username": [
            "The username has already been taken."
        ]
    }
}

我用JSONLint测试过JSON,它说JSON都很好

不工作-Laravel JSON响应

return response()->json([
       'access_token' => $tokenResult->accessToken,
        'token_type' => 'Bearer',
        'expires_at' => Carbon::parse(
            $tokenResult->token->expires_at
        )->toDateString()
        ], 200);

工作-Laravel JSON响应

    return response()->json([
        'message'=>'Cadastro realizado.',
        'user_id' => $user->id
    ], 201);

Android系统登录

btnSignin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d(TAG, "onClick: " + etSigninUser.getText().toString());
            Log.d(TAG, "onClick: " + etSigninPassword.getText().toString());
            Call<LoginResponse> call = apiService.userLogin(
                    etSigninUser.getText().toString(),
                    etSigninPassword.getText().toString(),
                    false
            );

            call.enqueue(new Callback<LoginResponse>() {
                @Override
                public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
                    Log.d(TAG, "onResponse: " + response.code());
                }

                @Override
                public void onFailure(Call<LoginResponse> call, Throwable t) {
                    Log.d(TAG, "onFailure: " + t.toString() + " " + t.getCause());
                    Log.d(TAG, "onFailure: " + t.toString());
                }
            });
        }
    });

Android-LoginResponse模型

    public class LoginResponse {

    @SerializedName("access_token")
    @Expose
    private String accessToken;
    @SerializedName("token_type")
    @Expose
    private String tokenType;
    @SerializedName("expires_at")
    @Expose
    private String expiresAt;

    public String getAccessToken() {
        return accessToken;
    }

    public void setAccessToken(String accessToken) {
        this.accessToken = accessToken;
    }

    public String getTokenType() {
        return tokenType;
    }

    public void setTokenType(String tokenType) {
        this.tokenType = tokenType;
    }

    public String getExpiresAt() {
        return expiresAt;
    }

    public void setExpiresAt(String expiresAt) {
        this.expiresAt = expiresAt;
    }
}

**Android-改装2呼叫**

@FormUrlEncoded
@POST("auth/login")
Call<LoginResponse> userLogin(
        @Field("username") String username,
        @Field("password") String password,
        @Field("remember_me") boolean remember_me
);

我看不出我的代码有什么问题,似乎一切都很好,为什么我会出现这个错误?JSON格式错误吗?

编辑1-邮递员

共有1个答案

严劲
2023-03-14

我有这个问题,花了我很多时间才弄明白。

我在这里找到了一个解决方案:https://stackoverflow.com/a/56903479/3971619

TLDR:用于创建改造对象的BASE_URL变量不应在/之后有任何内容

替换:

val authApiService = Retrofit.Builder()
    .baseUrl("https://test.com/api/test") //There is path after the /
    .addConverterFactory(GsonConverterFactory.create(gson))
    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
    .build().create(AuthService::class.java)

通过

val authApiService = Retrofit.Builder()
    .baseUrl("https://test.com/") //It should only be the base url without a path
    .addConverterFactory(GsonConverterFactory.create(gson))
    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
    .build().create(ServiceClass::class.java)
 类似资料: