首页 > 解决方案 > 没有键值的 JSON 序列化响应

问题描述

我正在使用改造来进行 http 调用,并使用 gson 来进行 json 解析。这是我的json

 {
"-109.457154947154,26.4155454751248": [
{
  "data": {
    "date": "2017-13-13",
    "source_type": "Light",
    "table_value": 3,
    "condition": "Good"
  }
},
{
  "data": {
    "date": "2019-11-15",
    "source_type": "Light",
    "table_value": 4,
    "condition": "Very good"
  }
},
{
  "data": {
    "date": "2019-11-15",
    "source_type": "Heavy",
    "table_value": 3,
    "condition": "Good"
  }
}
],
 "-110.2324214532214,27.9288762948267": [
 {
  "data": {
    "date": "2017-13-13",
    "source_type": "Light",
    "table_value": 3,
    "condition": "Good"
  }
},
{
  "data": {
    "date": "2019-11-15",
    "source_type": "Light",
    "table_value": 4,
    "condition": "Very good"
  }
},
{
  "data": {
    "date": "2019-11-15",
    "source_type": "Heavy",
    "table_value": 3,
    "condition": "Good"
  }
}
]
}

此响应没有顶级元素的键。我想序列化这个响应。

这是我的数据 object.class

public class Data {

/*
*  "data": {
    "date": "2017-13-13",
    "source_type": "Light",
    "table_value": 3,
    "condition": "Good"
  }
*
* */

@SerializedName("date")
@Expose
private String date;

@SerializedName("source_type")
@Expose
private String source_type;

@SerializedName("table_value")
@Expose
private String table_value;

@SerializedName("condition")
@Expose
private String condition;

public Data(String date, String source_type, String table_value, String condition) {
    this.date = date;
    this.source_type = source_type;
    this.table_value = table_value;
    this.condition = condition;
}
   // Getters and Setters
 }

由于我是 Android 开发的新手,我无法理解如何序列化其他元素。我知道我应该编写另一个模型类来解析这个 JSON 响应。但我无法弄清楚正确的做法。

标签: androidjsonretrofitokhttp

解决方案


“-109.4571...”、“-110.23...”是关键,而不是价值。如果你想得到钥匙,你可以在这里看到。

如果要解析对象,则应将 json 修复为:

{
    "string_key_1":"-109.457154947154,26.4155454751248",
    "string_key_2":[
        {
            "data": {
                "date": "2017-13-13",
                "source_type": "Light",
                "table_value": 3,
                "condition": "Good"
            }
        }
    ]
}

推荐阅读