【问题标题】:Android retrofit 2 | get list data from JSON response安卓改造2 |从 JSON 响应中获取列表数据
【发布时间】:2020-02-26 12:33:35
【问题描述】:

我正在使用改造 2。我正在进行 HTTP 调用并获取这种 JSON 数据作为响应:

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

我想获取这个 JSON 的上下文并将其呈现在一个数组中,但对于初学者来说,我不知道如何获取我的响应的上下文。我尝试使用 response.body() 但它似乎不起作用。 有我的代码:

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
                }
            })

而 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;
    }

还有我的 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)

}

关于如何访问数据以及如何将它们传递给表格数组布局的任何提示?

【问题讨论】:

    标签: android json kotlin gson retrofit2


    【解决方案1】:

    @ZookKep - response.body() 将返回对象列表。你可以直接使用它。不需要任何其他逻辑。

    我的意思是不要在 response.body() 上调用 .toString()。

    您可以通过如下方式查看日志

    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("----", "----")
           }
    }
    

    如果您对此仍有疑问,请在 cmets 部分告诉我。我很乐意提供帮助:)

    【讨论】:

    • 这给了我这个结果:[com.cge.cgeenergy.models.Response1@4b522a1]
    • 我有未解决的参考“actualTotalLoadByMonthValue”
    • 请检查更新后的答案。以前我忘了提到“${model.actualTotalLoadByMonthValue}”
    • 不幸的是我得到了 INDEX 0: MODEL 4264156.37
    • 这是您的 json 的第一个索引值 - "ActualTotalLoadByMonthValue": "4264156.37"。
    【解决方案2】:

    试试这个。

    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();
    }
    

    如果您有任何困惑,请告诉我。

    【讨论】:

    • 感谢您的回答!我应该在哪里试试这个?
    • 在你的if (response.isSuccessful)
    • 不起作用,可能是因为 Gson 表单(?)刚刚添加了我的请求管理器代码来提问。
    • 你在使用 GSON 吗?
    • 是的,我正在使用 GSON
    【解决方案3】:

    //如果你想在控制台中打印整个 JSON 从这里导入 gson 库: implementation 'com.google.code.gson:gson:2.8.6'

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

    【讨论】:

    • 如果你想要区域名称的值或任何值然后添加 response.get(0).getAreaName();
    • 因为您尝试在数组上使用 getareaname,所以请尝试使用 response.get(0).getareaname()
    猜你喜欢
    • 2017-04-19
    • 2017-07-02
    • 2016-03-23
    • 1970-01-01
    • 1970-01-01
    • 2017-07-26
    • 1970-01-01
    • 2017-04-22
    • 1970-01-01
    相关资源
    最近更新 更多