gson 改造预期为开始_OBJECT,但实际为STRING

i86rm4rw  于 2022-11-06  发布在  其他
关注(0)|答案(3)|浏览(161)

大家好,我是一个从Sqareup改造库的新手。我已经使用Laravel框架创建了一个Web服务。当我给予了一个错误的或格式不正确的电话号码时,它应该给我一个正确的错误,作为json。我正在尝试解析这个JSON响应:

{
    "message": "The given data was invalid.",
    "errors": {
        "mobile_number": [
            "The mobile number format is invalid.",
            "The mobile number must be 11 digits."
        ]
    }
}

下面是我的模型类:

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

import java.util.List;

public class LoginResult {
    @SerializedName("mobile_number")
    private String mobileNumber;
    private String action;
    @SerializedName("message")
    private String message;
    @SerializedName("errors")
    private Errors errors;

    public String getMobileNumber() {
        return mobileNumber;
    }

    public String getAction() {
        return action;
    }

    public String getMessage() {
        return message;
    }

    public Errors getErrors() {
        return errors;
    }

    public static class Errors {
        @SerializedName("mobile_number")
        @Expose
        private List<String> mobileNumber = null;

        public List<String> getMobileNumber() {
            return mobileNumber;
        }
    }
}

...

import com.google.gson.annotations.SerializedName;

public class Login {
    @SerializedName("mobile_number")
    private String mobileNumber;

    public String getMobileNumber() {
        return mobileNumber;
    }

    public Login(String mobileNumber) {
        this.mobileNumber = mobileNumber;
    }
}

我接口道:

import ir.husoft.kasbokar.models.Login;
import ir.husoft.kasbokar.models.LoginResult;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.POST;

public interface ApiInterface {
    @POST("api/auth/login")
    Call<LoginResult> login(@Body Login login);
}

下面是ApiClient:

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

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

public class ApiClient {
    public static final String BASE_URL = "http://127.0.0.1:8000/";
    public static Retrofit retrofit;

    public static Retrofit getApiClient() {
        if (retrofit == null) {
            Gson gson = new GsonBuilder().setLenient().create();
            retrofit = new Retrofit.Builder().baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create(gson)).build();
        }

        return retrofit;
    }
}

我成功方法:

ApiInterface api = ApiClient.getApiClient().create(ApiInterface.class);
String mobileNumber = etMobileNumber.getText().toString();
            Login login = new Login(mobileNumber);
            Call<LoginResult> verification = api.login(login);
            verification.enqueue(new Callback<LoginResult>() {
                @Override
                public void onResponse(Call<LoginResult> call, Response<LoginResult> response) {
                    if (response.isSuccessful()) {
                        Toast.makeText(LoginActivity.this, "Action is: " + response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(LoginActivity.this, "Error code: " + response.code(), Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(Call<LoginResult> call, Throwable throwable) {
                    Toast.makeText(LoginActivity.this, throwable.getLocalizedMessage(), Toast.LENGTH_LONG).show();
                }
            });

当我在我的成功方法上使用它时,它抛出错误
应为开始_OBJECT,但在第1行第1列为STRING
这是怎么了?

cbeh67ev

cbeh67ev1#

你有没有试过从LoginResult中删除private String mobileNumber,而且mobileNumber是一个数组或字符串列表。

3qpi33ja

3qpi33ja2#

我发现了这个问题。我忘了为请求设置标头。ApiInterface必须是这样的:

public interface ApiInterface {
    @Headers("Accept: application/json")
    @POST("api/auth/login")
    Call<LoginResult> login(@Body Login login);
}
ssgvzors

ssgvzors3#

尝试使用此代码注册GSON无法转换的数据类型,在我的示例中,它是模型类中CreatedDate字段的Instant数据类型。

Gson gson = new GsonBuilder().registerTypeAdapter(Instant.class, new JsonDeserializer<Instant>() {
            @Override
            public Instant deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                    throws JsonParseException {
                return Instant.parse(json.getAsString());
            }
        }).create();
        retrofitClient = new Retrofit.Builder()
                .baseUrl(Config.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(retroHttpClient)
                .build();

相关问题