Модификация Ожидается BEGIN_OBJECT, но был STRING - PullRequest
0 голосов
/ 19 марта 2020

Привет, ребята. Я новичок в модернизации библиотеки из Sqareup. Я создал веб-сервис, используя Laravel framework. Когда я даю неправильный или искаженный номер телефона, он должен дать мне правильную ошибку как 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();
                }
            });

Когда я использую его в моем методе успеха, он выдает ошибку

Ожидается BEGIN_OBJECT, но в строке 1 столбца 1 указано STRING 1

Что здесь не так?

Ответы [ 2 ]

0 голосов
/ 19 марта 2020

Я нашел проблему. Я забыл установить заголовки для запроса. ApiInterface должен выглядеть следующим образом:

public interface ApiInterface {
    @Headers("Accept: application/json")
    @POST("api/auth/login")
    Call<LoginResult> login(@Body Login login);
}
0 голосов
/ 19 марта 2020

Вы пытались удалить private String mobileNumber из LoginResult, также mobileNumber - это массив или список строк.

...