【问题标题】:Java - JSONObject Parsing only 1 string?Java - JSONObject 只解析 1 个字符串?
【发布时间】:2014-11-03 17:32:39
【问题描述】:

我对 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是一个数组,不要去掉数组符号(即'['和']')
  • 所以保持原样?
  • 您在循环中的哪个位置使用循环索引i?怎么知道要引用哪个数组元素?
  • @DwB 不会给我“A JSONObject 文本必须以'{'开头”错误吗?
  • [] 是 JSON 数组的标识时,为什么要删除它们?

标签: java json


【解决方案1】:

您的 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}

【讨论】:

    【解决方案2】:

    我通过将其用作 JSONArray 来修复我的代码(感谢 @HotLicks)

    JSONArray obj = new JSONArray(v);
                ArrayList<String> list = new ArrayList<String>();
    
                for(int i = 0 ; i < obj.length(); i++){
                    Logger.WriteOutput(obj.getJSONObject(i).getString(c), Logger.LogLevel.Info);
                }
    

    【讨论】:

      【解决方案3】:

      试试这个:

      // This line is useless
      // String output = v.replace("[", "").replace("]", "");
      JSONArray arr = new JSONArray(output);
      ArrayList<String> list = new ArrayList<String>();
      for(int i = 0 ; i < arr.length(); i++){
          System.out.println(arr.getJSONObject(i).getString(c));
          list.add(arr.getJSONObject(i).getString(c));
      }
      

      【讨论】:

        【解决方案4】:

        首先为您的 json 创建一个 java bean(例如 here):

        public class Item {
        
            @JsonProperty("id")
            private String  id;
            @JsonProperty("time")
            private Integer time;
        
            public final String getId() {
                return id;
            }
        
            public final void setId(String id) {
                this.id = id;
            }
        
            public final Integer getTime() {
                return time;
            }
        
            public final void setTime(Integer time) {
                this.time = time;
            }
        
        }
        

        如果您使用的是 Jackson Java JSON 处理器,您可以通过这种方式从 JSON-String 创建一个列表:

            ObjectMapper objectMapper = new ObjectMapper();
        
            try {
                List<Item> items = objectMapper.readValue(
                            yourJSONString, 
                            objectMapper.getTypeFactory().constructCollectionType(List.class, Item.class));
        
                for (Item item : items) {
                    System.out.println(item.getId());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        

        【讨论】:

        • 这里完全不需要创建bean。
        • @JonSkeet 品味问题
        • 对于给定的任务,对我来说似乎要付出更多的努力。 (在其他情况下,这当然是非常合适的——但是将您为 incomplete 程序提供的代码量与我的较短代码进行比较,后者是具有相同输出的独立程序。)跨度>
        • @JonSkeet 我相信 OP 想要(也许稍后)更多只是获得 ID。我试图提供一个通用的OO解决方案
        • 鉴于 OP 从该方法返回的只是一个 ID,并且他们描述了他们“找出它的 ID”的尝试,我认为这对于所描述的问题来说是过度工程。当然,他们可能以后会想要更多——在那个时候是合适的。但是虽然有一个更简单的解决方案,但我认为提出它是合理的:)
        【解决方案5】:

        使用下面的代码

        String v = "[{\"id\":\"ID1\",\"time\":123},{\"id\":\"ID2\",\"time\":124}]";
                String c = "id";
                JSONArray obj = null;
                try {
                    obj = new JSONArray(v);
        
                    ArrayList<String> list = new ArrayList<String>();
        
                    for (int i = 0; i < obj.length(); i++) {
                        JSONObject j = (JSONObject) obj.get(i);
                        System.out.println(j.getString(c));
                        list.add(j.getString(c));
                    }
        
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
        

        请注意,我也稍微修正了 json 结构

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

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

        【讨论】:

        • 拥有"{ID1}" 不会使 JSON 无效。
        • 你是对的 - 如果他故意考虑将“{ID1}”作为字符串。由于他对 JSON 很陌生,而且他的帖子只讨论了返回 ID1(不带大括号),所以我修改了输入字符串。
        猜你喜欢
        • 2013-08-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-23
        • 1970-01-01
        相关资源
        最近更新 更多