GSON - 使用地图将 JsonObject 转换为 java/Kotlin 对象

GSON - convert JsonObject to java/Kotlin object using a map

我想使用 Gson 将 jsonObject 转换为对象。但是,该对象没有针对某些项目的固定键。

{
  "hits": [],
  "target": {
    "geo": {
      "54.57982-24.41563": 891,
      "55.37717-25.30446": 725,
      "55.47091-25.31749": 569,
      "55.20887-25.05958": 514,
      "55.45714-25.29926": 494,
      "54.68297-24.34772": 406,
      "54.55594-24.33671": 314,
      "55.42375-25.22124": 295,
      "54.55434-24.33302": 277,
      "55.25917-25.11189": 266
    }
  }
}

如您所见,ge0 对象没有固定键。

试试下面的方法对你有帮助

JSONObject data = jsonResponse.getJSONObject("geo");// here response is server response
    Iterator keys = data.keys();

    while(keys.hasNext()) {
        // loop to get the dynamic key
        String key = (String)keys.next();  // it returns a key 

        // get the value of the dynamic key
        int value = data.getInt(key);      // it returns a value like 891,725 etc...

    }

你可以用HashMap代替它:-

data class Response(val hits: List<Any>, val target: Target) {
    data class Target(val geo: HashMap<String, Int>)
}

然后反序列化

val response: Response = gson.fromJson(jsonObjectInString.trim(), Response::class.java)

然后在地图上循环:-

for((latLong, value) in response.target.geo) {
     // work with your keys and values
}