Запрос Retrofit2 GET возвращает несколько пустых записей в списке при попытке получить массив JSON - PullRequest
0 голосов
/ 06 ноября 2019

Данные JSON:

[
  {
    "ID": 47,
    "lat": 20.2,
    "lon": 18.04308,
    "alt": "100",
    "location": "Location 001",
    "meinOrt": "Ort1",
    "meineBeschreibung": "wald",
    "satNr": "0"
  },
  {
    "ID": 47,
    "lat": 50,
    "lon": 28.04308,
    "alt": "134.5",
    "location": "Location 002",
    "meinOrt": "Ort2",
    "meineBeschreibung": "wald2",
    "satNr": "0"
  },
  {
    "ID": 47,
    "lat": 49.07458166666667,
    "lon": 16.04308,
    "alt": "134.5",
    "location": "Location 003",
    "meinOrt": "Ort3",
    "meineBeschreibung": "wald",
    "satNr": "0"
  },
  {
    "ID": 47,
    "lat": 46.07458166666667,
    "lon": 33.04308,
    "alt": "134",
    "location": "Location 004",
    "meinOrt": "Ort4",
    "meineBeschreibung": "wald",
    "satNr": "0"
  },
  {
    "ID": 47,
    "lat": 45,
    "lon": 24.2,
    "alt": "134.5",
    "location": "Location 005",
    "meinOrt": "Ort5",
    "meineBeschreibung": "wald",
    "satNr": "0"
  }
]

Интерфейс API:

    @GET("get_entries.php")
    Call<List<Entries>> getEntries();

Entries.java

class Entries {

    private int id;
    private String latitude;
    private String longitude;
    private String location;
    private String altitude;
    private String meinOrt;
    private String meineBeschreibung;
    private String myDatetime;



    public Entries(int id, String latitude, String longitude, String location, String altitude, String meinOrt, String meineBeschreibung, String myDatetime) {
        this.id = id;
        this.latitude = latitude;
        this.longitude = longitude;
        this.location = location;
        this.altitude = altitude;
        this.meinOrt = meinOrt;
        this.meineBeschreibung = meineBeschreibung;
        this.myDatetime = myDatetime;
    }

    public int getID() {
        Log.d("DEBUG", "in getID = " + latitude );
        return id;
    }

    public String getlatitude() {
        return latitude;
    }

    public String getlongitude() {
        return longitude;
    }

    public String getlocation() {
        return location;
    }

    public String getaltitude() {
        return altitude;
    }

    public String getmeinOrt() {
        return meinOrt;
    }

    public String getmeineBeschreibung() {
        return meineBeschreibung;
    }

    public String getmyDatetime() {
        return myDatetime;
    }
}

Orte.java (где был сделан вызов):

    private void getEntries() {

        textViewResult = findViewById(R.id.text_view_result);

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://myBaseUrlexample.de/api/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        JsonPlaceHolderApi jsonPlaceHolderApi = retrofit.create(JsonPlaceHolderApi.class);
        Log.d("DEBUG", "--> API CREATE  = " + jsonPlaceHolderApi );

        Call<List<Entries>> call = jsonPlaceHolderApi.getEntries();
        Log.d("DEBUG", "--> create call  = " + call );

        call.enqueue(new Callback<List<Entries>>() {
            @Override
            public void onResponse(Call<List<Entries>> call, Response<List<Entries>> response) {
                Log.d("DEBUG", "--> on response  = " + call );
                if (!response.isSuccessful()) {
                    textViewResult.setText("Code: " + response.code());
                    return;
                }


                List<Entries> alleEintraege = response.body();

                Log.d("DEBUG", "--> API CREATE  = " + alleEintraege );

                for (Entries einzeleintrag : alleEintraege) {

                    String content = "";
                    content += "ID: " + einzeleintrag.getID() + "\n";
                    content += "Lat: " + einzeleintrag.getlatitude() + "\n";
                    content += "Lon: " + einzeleintrag.getlongitude() + "\n";
                    content += "Ort: " + einzeleintrag.getmeinOrt() + "\n";
                    //content += "Entfernung: " + distance + "\n";
                    content += "Location: " + einzeleintrag.getlocation() + "\n";
                    content += "Höhe: " + einzeleintrag.getmyDatetime() + "\n";
                    content += "Beschreibung: " + einzeleintrag.getmeineBeschreibung() + "\n\n";

                    textViewResult.append(content);
                }
            }

            @Override
            public void onFailure(Call<List<Entries>> call, Throwable t) {
                textViewResult.setText(t.getMessage());
            }
        });
    }

Logcat:


11-06 08:11:18.702 5803-5803/com.example.mikkigpsv4 D/DEBUG: --> API CREATE  = retrofit2.Retrofit$1@25f1b684
11-06 08:11:18.713 5803-5803/com.example.mikkigpsv4 D/DEBUG: --> create call  = retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall@208d07a1
11-06 08:11:18.873 5803-5803/com.example.mikkigpsv4 D/DEBUG: --> on response  = retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall@208d07a1
11-06 08:11:18.873 5803-5803/com.example.mikkigpsv4 D/DEBUG: --> API CREATE  = [com.example.mikkigpsv4.Entries@1cf2c6e4, com.example.mikkigpsv4.Entries@450574d, com.example.mikkigpsv4.Entries@235cd202, com.example.mikkigpsv4.Entries@60e3713, com.example.mikkigpsv4.Entries@14876d50]

Результат на моем мобильном телефоне:

ID: 0 Lat: null Lon: null Ort: Ort1 Location: Location001Höhe: null Beschreibung: wald

ID: 0 Lat: null Lon: null Ort: Ort2 Location: Location002 Höhe: null Beschreibung: wald2

ID: 0 Lat: null Lon: null Ort:Ort3 Местоположение: Location003 Höhe: null Beschreibung: wald

ID: 0 Lat: null Lon: null Ort: Ort4 Location: Location004 Höhe: null Beschreibung: wald

ID: 0 Lat: null Lon: null Ort: Ort5 Местоположение: Location005 Höhe: null Beschreibung: waldschreibung: wald

Таким образом, некоторые записи получают хорошие ответы, а некоторые только обнуляются, любая помощь в получении этих записей будет оценена по достоинству. Спасибо.

Ответы [ 3 ]

3 голосов
/ 06 ноября 2019

Используйте Gson @SerializedName("") в вашей модели, чтобы сопоставить ключ с json

@SerializedName("ID")
private int id;
@SerializedName("lat")
private String latitude;
@SerializedName("lon")
private String longitude;
@SerializedName("location")
private String location;
@SerializedName("alt")
private String altitude;
@SerializedName("meinOrt")
private String meinOrt;
@SerializedName("meineBeschreibung")
private String meineBeschreibung;
@SerializedName("satNr")
private String myDatetime;
0 голосов
/ 06 ноября 2019

Проблема заключается в том, что Retrofit использует GsonConvertor для преобразования (объект JSON в POJO) сериализации. Для этого вы должны дать одно и то же имя в объекте JSON и в объекте POJO, который вы создали.

В качестве ответа @ Md.Asaduzzaman вы можете использовать @SerializedName("---") или переименовать ваш член класса POJO, чтобы соответствоватьс ответом JSON.

i.e latitude to lat

0 голосов
/ 06 ноября 2019

Используйте jsonschema2pojo для генерации вашей модели, которая должна быть:

Это должен быть "ID", а не "id"

public class Example {

@SerializedName("ID")
@Expose
private Integer iD;
@SerializedName("lat")
@Expose
private Integer lat;
@SerializedName("lon")
@Expose
private Double lon;
@SerializedName("alt")
@Expose
private String alt;
@SerializedName("location")
@Expose
private String location;
@SerializedName("meinOrt")
@Expose
private String meinOrt;
@SerializedName("meineBeschreibung")
@Expose
private String meineBeschreibung;
@SerializedName("satNr")
@Expose
private String satNr;

public Integer getID() {
return iD;
}

public void setID(Integer iD) {
this.iD = iD;
}

public Integer getLat() {
return lat;
}

public void setLat(Integer lat) {
this.lat = lat;
}

public Double getLon() {
return lon;
}

public void setLon(Double lon) {
this.lon = lon;
}

public String getAlt() {
return alt;
}

public void setAlt(String alt) {
this.alt = alt;
}

public String getLocation() {
return location;
}

public void setLocation(String location) {
this.location = location;
}

public String getMeinOrt() {
return meinOrt;
}

public void setMeinOrt(String meinOrt) {
this.meinOrt = meinOrt;
}

public String getMeineBeschreibung() {
return meineBeschreibung;
}

public void setMeineBeschreibung(String meineBeschreibung) {
this.meineBeschreibung = meineBeschreibung;
}

public String getSatNr() {
return satNr;
}

public void setSatNr(String satNr) {
this.satNr = satNr;
}

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...