Получение данных в Json с использованием Retrofit - PullRequest
0 голосов
/ 27 марта 2019

Ожидается BEGIN_ARRAY, но в строке 3 столбца 26 путь $ [0] .данных

public class MainActivity extends AppCompatActivity {

    Api_Interface api_interface;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        api_interface=ApiClient.getClient().create(Api_Interface.class);

        Call<List<CountryClas>> call=api_interface.getcountry("GetCountry","727","cl1oEntQ32PxZsS3VJnC+H+CY5oLfFLRU5j1H4bg+1g=");




      call.enqueue(new Callback<List<CountryClas>>() {
            @Override
            public void onResponse(Call<List<CountryClas>> call, Response<List<CountryClas>> response) {
                Log.e("Res",">>>>>>"+response.body());
                }

            @Override
            public void onFailure(Call<List<CountryClas>> call, Throwable t) {
                Log.e("Error",">>>>>>"+t.getMessage());
            }
        });
    }

}

InterFace

public interface Api_Interface {

@GET("json.php")
Call<List<CountryClas>> getcountry(@Query("action") String action, @Query("umID") String umID
        , @Query("OauthToken") String OauthToken);

}

ApiClient

public class ApiClient {
    private static final String BaseUrl="http://23.227.133.210/consultapro/";

    private static Retrofit retrofit=null;

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

Класс модели

public class CountryClas {

    @SerializedName("status")
    @Expose
    private Boolean status;
    @SerializedName("data")
    @Expose
    private List<Datum> data = null;
    @SerializedName("message")
    @Expose
    private String message;

    public Boolean getStatus() {
        return status;
    }

    public void setStatus(Boolean status) {
        this.status = status;
    }

    public List<Datum> getData() {
        return data;
    }

    public void setData(List<Datum> data) {
        this.data = data;
    }

    public String getMessage() {
        return message;
    }

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

}

Второй класс модели

public class Datum {

    @SerializedName("Country_Id")
    @Expose
    private String countryId;
    @SerializedName("Country_Name")
    @Expose
    private String countryName;
    @SerializedName("Country_Code")
    @Expose
    private String countryCode;

    public String getCountryId() {
        return countryId;
    }

    public void setCountryId(String countryId) {
        this.countryId = countryId;
    }

    public String getCountryName() {
        return countryName;
    }

    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }

    public String getCountryCode() {
        return countryCode;
    }

    public void setCountryCode(String countryCode) {
        this.countryCode = countryCode;
    }

}

// Json Response

[{"status": true, "data": [{"Country_Id": "101", "Country_Name": "India", "Country_Code": "91"}, {"Country_Id":"231", "Country_Name": "Соединенные Штаты", "Country_Code": "1"}, {"Country_Id": "230", "Country_Name": "United Kingdom", "Country_Code": "44"}],"message": "Список стран найден."}]

Ответы [ 5 ]

1 голос
/ 27 марта 2019

'Ожидаемый BEGIN_ARRAY, но был STRING' означает, что ваша переменная-член, для которой вы определили тип данных, не совпадает, ожидается, что String [] может быть, и вы могли использовать Sting , пожалуйста, перепроверьте.

0 голосов
/ 18 апреля 2019
//There are some issue to define in InterFace here is code

public interface Api_Interface {

    @FormUrlEncoded
    @POST("json.php")
    Call<List<CountryClas>> getcountry(@Field("action") String action, @Field("umID") String umID
        , @Field("OauthToken") String OauthToken);
}
0 голосов
/ 27 марта 2019

вы можете преобразовать ваше тело ответа в Java Objects / List, используя Gson.Смотрите пример кода ниже

req.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {

            BufferedReader reader = null;
            StringBuilder sb = new StringBuilder();
            reader = new BufferedReader(new InputStreamReader(response.body().byteStream()));
            String line;
            try {
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            String result = sb.toString();

            ApiResponse apiResponse = new Gson().fromJson(result, ApiResponse.class);
0 голосов
/ 27 марта 2019

Я пытаюсь подключить ваш API без аутентификации

http://23.227.133.210/consultapro/json.php?action=getCountry * * 1004

тогда я получаю ответ как это

[{"status":false,"data":"-->getCountry-->3JfalKdsUf15fsfGIwjcXg== -->","message":"User is not authenticated."}]

в данных, он возвращает String вместо ARRAY

Так что я думаю, потому что вы запрашиваете с неверная аутентификация Это сделает вашу модель неверной -> JsonParseException

Извините за мой плохой английский

0 голосов
/ 27 марта 2019

Это означает, что ваша модель данных Json неверна.Просто используйте онлайн-конвертер json в Java для создания модели, если вы не знаете, в чем дело.

попробуйте этот конвертер

Эта модель на самом деле должна работать, если вы написали правильноСтрока Json

class Country {
@SerializedName("status")
private Boolean status;

@SerializedName("data")
private List<Data> data = null;

@SerializedName("message")
private String message;

public class Data {
    @SerializedName("Country_Id")
    private String countryId;

    @SerializedName("Country_Name")
    private String countryName;

    @SerializedName("Country_Code")
    private String countryCode;
}}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...