简体   繁体   English

安卓改造2 | 从 JSON 响应中获取列表数据

[英]Android retrofit 2 | get list data from JSON response

I'm using retrofit2.我正在使用改造2。 I'm making HTTP calls and get this kind of JSON data as a response:我正在进行 HTTP 调用并获取这种 JSON 数据作为响应:

[
    {
        "ActualTotalLoadByMonthValue": "4264156.37",
        "AreaName": "Hungary",
        "AreaTypeCode": "CTY",
        "Dataset": "ActualTotalLoad",
        "MapCode": "HU",
        "Month": "1",
        "ResolutionCode": "PT15M",
        "Source": "entso-e",
        "Year": "2018"
    }
]

I want to take the context of this JSON and present it in an array, but for starters I don't know how to get the context of my response.我想获取这个 JSON 的上下文并将其呈现在一个数组中,但对于初学者来说,我不知道如何获取我的响应的上下文。 I tried with response.body() but it doesn't seem to work.我尝试使用 response.body() 但它似乎不起作用。 There is my code:有我的代码:

val call = RequestManager.service.getactualtotalload(areaName,resolution, datetype ,"2018")
            call.enqueue(object : Callback<List<Response1>> {
                override fun onResponse(call: Call<List<Response1>>, response: Response<List<Response1>>)
                {
                    loaderout.visibility = View.GONE
                    if (response.isSuccessful) {
                        Log.d("deee","Json " + response.body().toString())
                        openTableActivity()
                    } else {
                    }
                }

                override fun onFailure(call: Call<List<Response1>>, t: Throwable) {
                    loaderout.visibility = View.GONE
                }
            })

while Response1 is like this:而 Response1 是这样的:

public class Response1 {

    @SerializedName("ActualTotalLoadByMonthValue")
    @Expose
    private String actualTotalLoadByMonthValue;
    @SerializedName("AreaName")
    @Expose
    private String areaName;
    @SerializedName("AreaTypeCode")
    @Expose
    private String areaTypeCode;
    @SerializedName("Dataset")
    @Expose
    private String dataset;
    @SerializedName("MapCode")
    @Expose
    private String mapCode;
    @SerializedName("Month")
    @Expose
    private String month;
    @SerializedName("ResolutionCode")
    @Expose
    private String resolutionCode;
    @SerializedName("Source")
    @Expose
    private String source;
    @SerializedName("Year")
    @Expose
    private String year;

    public String getActualTotalLoadByMonthValue() {
        return actualTotalLoadByMonthValue;
    }

    public void setActualTotalLoadByMonthValue(String actualTotalLoadByMonthValue) {
        this.actualTotalLoadByMonthValue = actualTotalLoadByMonthValue;
    }

    public String getAreaName() {
        return areaName;
    }

    public void setAreaName(String areaName) {
        this.areaName = areaName;
    }

    public String getAreaTypeCode() {
        return areaTypeCode;
    }

    public void setAreaTypeCode(String areaTypeCode) {
        this.areaTypeCode = areaTypeCode;
    }

    public String getDataset() {
        return dataset;
    }

    public void setDataset(String dataset) {
        this.dataset = dataset;
    }

    public String getMapCode() {
        return mapCode;
    }

    public void setMapCode(String mapCode) {
        this.mapCode = mapCode;
    }

    public String getMonth() {
        return month;
    }

    public void setMonth(String month) {
        this.month = month;
    }

    public String getResolutionCode() {
        return resolutionCode;
    }

    public void setResolutionCode(String resolutionCode) {
        this.resolutionCode = resolutionCode;
    }

    public String getSource() {
        return source;
    }

    public void setSource(String source) {
        this.source = source;
    }

    public String getYear() {
        return year;
    }

    public void setYear(String year) {
        this.year = year;
    }

Also my RequestManager:还有我的请求管理器:

object RequestManager {
    val interceptor = HttpLoggingInterceptor()
    val client = OkHttpClient.Builder().addInterceptor(interceptor).build()


    init {
        //TODO must be None at live
        interceptor.level = HttpLoggingInterceptor.Level.BODY
    }


    val retrofit = Retrofit.Builder()
        .baseUrl("http://c6913be7.ngrok.io/energy/api/")
        .addConverterFactory(GsonConverterFactory.create())
        .client(client)
        .build()

    val service = retrofit.create(Api::class.java)

}

Any tips on how to access the data and then how to pass them on to a table array layout?关于如何访问数据以及如何将它们传递给表数组布局的任何提示?

@ZookKep - response.body() will return list of objects. @ZookKep - response.body() 将返回对象列表。 You can directly use that.你可以直接使用它。 Don't need to any other logic.不需要任何其他逻辑。

I mean don't make .toString() call on response.body().我的意思是不要在 response.body() 上调用 .toString()。

You can check with log like follows您可以查看日志如下

val listOfModels = response.body()

if (listOfModels != null) {
    for ((index, model) in listOfModels.withIndex()) {
        Log.d("----", "----")
        Log.d("INDEX $index", "ActualTotalLoadByMonthValue ${model.actualTotalLoadByMonthValue}")
        Log.d("INDEX $index", "AreaName ${model.areaName}")
        Log.d("INDEX $index", "AreaTypeCode ${model.areaTypeCode}")
        Log.d("INDEX $index", "Dataset ${model.dataset}")
        Log.d("INDEX $index", "MapCode ${model.mapCode}")
        Log.d("INDEX $index", "Month ${model.month}")
        Log.d("INDEX $index", "ResolutionCode ${model.resolutionCode}")
        Log.d("INDEX $index", "Source ${model.source}")
        Log.d("INDEX $index", "Year ${model.year}")
        Log.d("----", "----")
       }
}

Still you have doubt on this please let me know in comments section.您仍然对此有疑问,请在评论部分告诉我。 I am happy to help :)我很乐意提供帮助:)

Try this.尝试这个。

try {
    // jsonString is a string variable that holds the JSON 
    JSONArray itemArray = new JSONArray(jsonString);
    for (int i = 0; i < itemArray.length(); i++) {
        int value=itemArray.getInt(i);
        Log.e("json","json array value for " +  i + " = " + value);
    }
} catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

Let me know if you have any confusion.如果您有任何困惑,请告诉我。

//if you want to print the whole JSON in console import gson liabrary from here: implementation 'com.google.code.gson:gson:2.8.6' //如果你想在控制台中打印整个 JSON 导入 gson library from here: implementation 'com.google.code.gson:gson:2.8.6'

if (response.isSuccessful) {

     foreach(Response model:Response1){
     Log.e("value",model.getYourMethod());
     }
}

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

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