【问题标题】:How to convert jsonstring to jsonobject in android?如何在android中将jsonstring转换为jsonobject?
【发布时间】:2018-01-06 18:01:00
【问题描述】:

我尝试将 jsonstring 转换为 json 对象。但它只转换第一个元素。

这是我的代码

String d = [{"name":"kd","isMe":"yes","time":"10:12 AM"},{"name":"you","isMe":"no","time":"10:12 AM"}]
JSONObject j = new JSONObject(d);

它给出以下输出

{"name":"kd","isMe":"yes","time":"10:12 AM"}

如何将此字符串转换为 JSNOObject?

【问题讨论】:

  • 您应该将 JSON 对象转换为 JSON 数组。遍历数组,然后打印它。

标签: java android json


【解决方案1】:

你可以这样试试,你的根是Json数组而不是jsonobject

try {
    JSONArray jsonArray = new JSONArray(d);
    if(jsonArray != null) {
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.optJSONObject(i);

            if(jsonObject == null) {
                continue;
            }

            String name = jsonObject.optString("name");
            String isMe = jsonObject.optString("isMe");
            String time = jsonObject.optString("time");

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

【讨论】:

    【解决方案2】:

    使用这个

    JSONObject jsonObject = new JSONObject(my_json_string);
    JSONArray jresult = jsonObject.getJSONArray("array_in_the_json_string");
    

    【讨论】:

      猜你喜欢
      • 2011-07-11
      • 1970-01-01
      • 2021-11-17
      • 2023-03-24
      • 1970-01-01
      • 2016-12-21
      • 2017-07-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多