【问题标题】:How to GET data from single value inside JSON Object from JSON Array?如何从 JSON 数组中的 JSON 对象中的单个值获取数据?
【发布时间】:2021-11-24 13:31:32
【问题描述】:

我是 Kotlin 初学者,正在尝试创建代码以从 JSON 中获取数据。

我想从“forecastMaxtemp”中的“value”获取数据。

这是我的代码。我尝试如下但不成功。

...
Response.Listener { response ->
temp.text = 
response.getJSONArray (name"weatherForecast").
    getJSONObject(0).
    getJSONObject("forecastMaxtemp").
    getString(name"value")
},

JSON 数据

{"generalSituation":No Alarm",
"weatherForecast":[{
    "forecastDate":"20211004",
    "week":"Monday",
    "forecastWind":"East force 4 to 5.",
    "forecastWeather":"Sunny periods.",
    "forecastMaxtemp":{"value":31,"unit":"C"},
    "forecastMintemp":{"value":27,"unit":"C"},
...
...
]
}

【问题讨论】:

  • 感谢您的建议我该如何修改它如果我想在一个 JSONObject 中获取两个值(“值”和“单位”)

标签: android json kotlin


【解决方案1】:

{"value":31,"unit":"C"} 这里31 是int,所以使用getInt() 函数。

response.getJSONArray ("weatherForecast").
getJSONObject(0).
getJSONObject("forecastMaxtemp").
getInt("value")
}

【讨论】:

    【解决方案2】:

    您的 JSON 有问题,我认为这是正确的格式:

    {
      "generalSituation": "No Alarm",
      "weatherForecast": [
        {
          "forecastDate": "20211004",
          "week": "Monday",
          "forecastWind": "East force 4 to 5.",
          "forecastWeather": "Sunny periods.",
          "forecastMaxtemp": {
            "value": 31,
            "unit": "C"
          },
          "forecastMintemp": {
            "value": 27,
            "unit": "C"
          }
        }
      ]
    }
    

    从“forecastMaxtemp”中获取值,

    val json = JSONObject("YOUR_JSON")
    val obj = json.getJSONArray("weatherForecast").get(0) as JSONObject
    val value = obj.getJSONObject("forecastMaxtemp").getInt("value")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-31
      • 1970-01-01
      • 1970-01-01
      • 2020-09-28
      相关资源
      最近更新 更多