简体   繁体   English

我想从使用Retrofit2获得的json数组中获取特定对象的列表。 我该怎么做呢?

[英]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; Json结构 PS该引用不是动态的,因此只有一个JSON数据数组。

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 : 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 : 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 : JsonPlaceApi.java:

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

Pandomats.java : 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? 我需要用getModel填充列表,例如如何实现它或出现错误?

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. 通过查看您在问题中发布的示例JSON数据格式,我认为API不会返回JSONArray,而是会返回JSONObject Anyway I'll tell you how to get the required data from parsed objects whether it's JSONArray or JSONObject. 无论如何,我都会告诉您如何从解析的对象中获取所需的数据,无论是JSONArray还是JSONObject。

You're almost near to the solution you're searching for. 您几乎可以找到所需的解决方案。 Just paste the below code inside onResponse() method. 只需将以下代码粘贴到onResponse()方法中即可。

@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. 像上面一样,您可以从Pandomats类中获取任何对象。 Make sure the you've initialized pandomats ArrayList at the time of declaration or before using it inside onResponse() method. 确保在声明时或在onResponse()方法中使用pandomats ArrayList之前已初始化它。 Otherwise you'll end-up with NullPointerException . 否则,您将最终遇到NullPointerException

And also don't forget to log the error response from API inside onFailure() method. 并且也不要忘记在onFailure()方法中记录来自API的错误响应。 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. 如前所述,我认为API不会返回JSONArray而是重新运行JSONObject。 If it's returning JSONObject, you need to change the code like below. 如果返回的是JSONObject,则需要更改如下代码。

JSONApi.java JSONApi.java

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

MainActivity.java 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. 如果不理解,请编辑问题并发布错误日志。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用Spring RestTemplate从其他对象中的数组中获取JSON对象的列表? - How do I get a list of JSON objects out of an array among other objects using Spring RestTemplate? 如何从 Retrofit onResponse 获取数据 - How do I get a data from a Retrofit onResponse 如何将文本文件中的特定行放入数组列表? - How do I get a specific line from a text file into an array list? 如何解析此 JSON object 以获取我可以使用的配方对象列表? - How do I parse this JSON object to get a list of recipe objects that I can then use? 我想检查一列是否在实体对象列表中具有特定值。我该怎么做? - I want to check if a column has specific values in list of entity objects.?How can i do that? 如何使用Retrofit 2解析嵌套对象? - How do I parse nested objects with Retrofit 2? 如何标记json对象数组? - How do I tokenize array of json objects? 如何获取JSON数组内部的JSON对象 - How do I get the JSON object which is inside of JSON array 如何获取Web应用程序中所有HttpSession对象的列表? - How do I get a list of all HttpSession objects in a web application? 我如何忽略 JSON 响应中列表中的特定字段 - How do i ignore a specific field from an list in JSON response
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM