Java - JSONObject 仅解析 1 个字符串?

标签 java json

我对 Java 中的 JSON 解析相当陌生,但是当我尝试解析这个 JSON 字符串并发现它是“ID”时,它会重复相同的两次。

[
  {"id":"{ID1}","time":123},
  {"id":"{ID2}","time":124}
]

这是我的 Java 代码:

        // v = json string, c = "id"
        String output = v.replace("[", "").replace("]", "");  
        JSONObject obj = new JSONObject(output);
        ArrayList<String> list = new ArrayList<String>();

        for(int i = 0 ; i < obj.length(); i++){
            System.out.println(obj.getString(c));
            list.add(obj.getString(c));
        }

        return list.get(1);

它返回 ID1 两次或多次。请帮忙

最佳答案

你的 JSON 代表一个数组 - 所以这就是你应该如何解析它。然后,您可以轻松地从数组中的每个 JSONObject 获取 id 属性。例如:

import org.json.*;

public class Test {
    public static void main(String[] args) throws JSONException {
        String json = 
            "[{\"id\":\"{ID1}\",\"time\":123}, {\"id\":\"{ID2}\",\"time\":124}]";
        JSONArray array = new JSONArray(json);

        for (int i = 0; i < array.length(); i++) {
            JSONObject o = array.getJSONObject(i);
            System.out.println(o.getString("id"));
        }
    }
}

输出:

{ID1}
{ID2}

关于Java - JSONObject 仅解析 1 个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26719669/

相关文章:

java - @ControllerAdvice,如何获取调用该方法的类?

java - 在流 API 收集器中求和 BigDecimals

php - 我应该在 CouchDB/Ajax 应用程序中使用 PHP 中的数组还是对象?

php - 在Elasticsearch中使用嵌套文档聚合多个存储桶

json - 在 Scala 中,如何为 Map[IndexedSeq[String], Int] 编写高效的 json 格式化程序?

java - 需要 java applet 来帮助测试屏幕阅读器

java - 图片上传到服务器的php错误响应= httpclient.execute(httppost);

java - 如何使用gson将对象转换为数组

java - 错误 : How to read empty cell in Excel

json - map[string] struct inside struct