简体   繁体   中英

I want to get a list of specific objects from the json array that I get with Retrofit2. how do I do this?

Json structure PS The reference is not dynamic so there is just a JSON data array;

I do everything on documentation but I receive simply an array and I cannot take from it the list of separate elements for example coordinates which are in this array

MainActivity.class :

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);





    Service.getInstance()
            .getJSONApi()
            .loadList()
            .enqueue(new Callback<List<Pandomats>>() {


                @Override
                public void onResponse(Call<List<Pandomats>> call, Response<List<Pandomats>> response) {
                    pandomats.addAll(response.body());



                    Log.v("ListPandomats", String.valueOf(pandomats.size()));
                }

                @Override
                public void onFailure(Call<List<Pandomats>> call, Throwable t) {

                }
            });

Service.java :

public class Service {
private static final Service ourInstance = new Service();
private static final String BASE_URL = "http://myurl";
private Retrofit mRetrofit;

public static Service getInstance() {
    return ourInstance;
}

private Service() {
    mRetrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

}

public JsonPlaceApi getJSONApi() {
    return mRetrofit.create(JsonPlaceApi.class);
}

}

JsonPlaceApi.java :

public interface JsonPlaceApi {
@GET("/api/device/get/")
Call<List<Pandomats>> loadList();
}

Pandomats.java :

    public class Pandomats {
    @SerializedName("id")
    @Expose
    private String address;
    @SerializedName("model")
    @Expose
    private String model;
    @SerializedName("latitude")
    @Expose
    private Double latitude;
    @SerializedName("longitude")
    @Expose
    private Double longitude;
    @SerializedName("lastDeviceData")
    @Expose
    private LastDeviceData lastDeviceData;
    @SerializedName("image")
    @Expose
    private Object image;



    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getModel() {
        return model;
    }

    public void setModel(String model) {
        this.model = model;
    }

    public Double getLatitude() {
        return latitude;
    }

    public void setLatitude(Double latitude) {
        this.latitude = latitude;
    }

    public Double getLongitude() {
        return longitude;
    }

    public void setLongitude(Double longitude) {
        this.longitude = longitude;
    }


    public LastDeviceData getLastDeviceData() {
        return lastDeviceData;
    }

    public void setLastDeviceData(LastDeviceData lastDeviceData) {
        this.lastDeviceData = lastDeviceData;
    }
    public Object getImage() {
        return image;
    }

    public void setImage(Object image) {
        this.image = image;
    }

}

I need my list to be filled with getModel for example how do I implement it or where I have an error?

By looking into the sample JSON data format you've posted in your question I don't think that API is returning JSONArray it returns JSONObject instead. Anyway I'll tell you how to get the required data from parsed objects whether it's JSONArray or JSONObject.

You're almost near to the solution you're searching for. Just paste the below code inside onResponse() method.

@Override
public void onResponse(Call<List<Pandomats>> call, Response<List<Pandomats>> response) {
     pandomats.addAll(response.body());
     Log.v("ListPandomats", String.valueOf(pandomats.size()));

     for (int i = 0; i < pandomats.size(); i++) {
         Pandomats p = pandomats.get(i);

         Log.v("ListPandomats", p.getModel());   // prints model
         Log.v("ListPandomats", String.valueOf(p.getLatitude()));   // prints latitude
     }
}

Like above you can get any object from Pandomats class. Make sure the you've initialized pandomats ArrayList at the time of declaration or before using it inside onResponse() method. Otherwise you'll end-up with NullPointerException .

And also don't forget to log the error response from API inside onFailure() method. It's very important.

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

As I said before I think that API is not returning JSONArray instead it reruns JSONObject. If it's returning JSONObject, you need to change the code like below.

JSONApi.java

public interface JsonPlaceApi {
    @GET("/api/device/get/")
    Call<Pandomats> loadList();  // remove List<> from return type 
}

MainActivity.java

Service.getInstance()
    .getJSONApi()
    .loadList()
    .enqueue(new Callback<Pandomats>() {  /* remove List<> */

        @Override
        public void onResponse(Call<Pandomats> call, /* remove List<> */ Response<List<Pandomats>> response) {
            Pandomats p = response.body();

            // without for loop iteration you can get the data
            Log.v("ListPandomats", p.getModel());   // prints model
            Log.v("ListPandomats", String.valueOf(p.getLatitude()));   // prints latitude
        }

        @Override
        public void onFailure(Call<Pandomats> call, Throwable t) { /* remove List<> */
            Log.e("ListPandomats", "Error" t);
        }
    });

I hope it's clear now. If you get the error, just look into error log first. If don't understand it, edit the question and post error logs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM