【问题标题】:How to convert JSON to array without using Gson如何在不使用 Gson 的情况下将 JSON 转换为数组
【发布时间】:2018-03-19 08:28:13
【问题描述】:

我有这个 JSON 对象:

{"home_device_name":"light","light_status":[{"id_light":"1","status":"1"},{"id_light":"2","status":"0"}]}

我将它作为 JSON 对象读取,但我无法访问“light_status”,我想将其转换为数组以便能够读取它。

【问题讨论】:

  • 如果你想在 Kotlin 中阅读,你真的应该使用像 Gson 或 Jackson 这样的 Json 解析器。
  • 为什么不将light_status 作为一个 json 数组并遍历每个对象并手动将它们转换为您想要的列表?
  • light_status 已经是可读格式。显示代码你如何阅读 json
  • 这可能很傻,但你为什么不想使用 Gson 呢?

标签: android json kotlin


【解决方案1】:

使用以下代码:

    String str = "{\"home_device_name\":\"light\",\"light_status\":[{\"id_light\":\"1\",\"status\":\"1\"},{\"id_light\":\"2\",\"status\":\"0\"}]}";

    try {
        JSONObject jsonObject = new JSONObject(str);

        String home_device_name = jsonObject.getString("home_device_name");

        JSONArray jsonArray = jsonObject.getJSONArray("light_status");

        for (int i = 0; i < jsonArray.length(); i++) {
            String id_light = jsonArray.getJSONObject(i).getString("id_light");
            String status = jsonArray.getJSONObject(i).getString("status");

            Log.d("Value", "Pos = " + i + " id_light = " + id_light + " status = " + status);
        }


    } catch (JSONException e) {
        e.printStackTrace();
    }

【讨论】:

  • 我认为他期待在 Kotlin 中得到答案。
【解决方案2】:

首先将以下模型添加到您的项目中

    class LightStatus {

    var idLight: String? = null
    var status: String? = null

}

现在您可以使用以下代码获取光阵列

    fun getLightArray() :ArrayList<LightStatus>{
    val jsonString = "{\"home_device_name\":\"light\",\"light_status\":[{\"id_light\":\"1\",\"status\":\"1\"},{\"id_light\":\"2\",\"status\":\"0\"}]}";
    val jsonObject=JSONObject(jsonString)
    val jsonArray =jsonObject.getJSONArray("light_status")
    val lightArray =ArrayList<LightStatus>()

    for (i in 0..jsonArray.length()-1){
        val lightStatus=LightStatus()
        lightStatus.idLight=jsonArray.getJSONObject(i).getString("id_light")
        lightStatus.status=jsonArray.getJSONObject(i).getString("status")
        lightArray.add(lightStatus)
    }
    return lightArray
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-29
    • 2014-02-08
    • 2016-05-07
    • 1970-01-01
    • 2021-04-12
    • 2020-08-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多