我正在使用 org.json 中的库解析这个 JSON 字符串,我不明白为什么我将下面的输出放入日志中。
ArrayList<String> al = new ArrayList<String>();
JSONObject demo = new JSONObject("{\"00408C88A2E6\":{\"id\":\"00408C88A2E6\",\"name\":\"Lab\"},\"00408C91188B\":{\"id\":\"00408C91188B\",\"name\":\"Lab1\"},\"00408C944B99\":{\"id\":\"00408C944B99\",\"name\":\"Lato1\"},\"00408C944BA0\":{\"id\":\"00408C944BA0\",\"name\":\"Lato\"}}");
Iterator<String> iterator = demo.keys();
while (iterator.hasNext() ){
al.add((String)iterator.next());
Log.i(LOG_TAG, "size al into while " + al.size());
Log.i(LOG_TAG, "MAC " + iterator.next() + " for the user " + userId);
}
日志输出
07-12 08:55:34.056: INFO/parse(285): size al into while 1
07-12 08:55:34.056: INFO/parse(285): MAC 00408C91188B for the user nweb
07-12 08:55:34.066: INFO/parse(285): size al into while 2
07-12 08:55:34.066: INFO/parse(285): MAC 00408C944B99 for the user nweb
07-12 08:55:34.066: INFO/parse(285): size al 2
我的 ArrayList 中不应该有 4 个元素吗? 谢谢
最佳答案
你打给了iterator.next()
在循环体内两次。每次这样做,迭代器都会向前推进。
您可能希望在正文中调用一次并将其存储在局部变量中。
String next = iterator.next();
al.add(next);
Log.i(LOG_TAG, "MAC " + next + " for the user " + userId);
请注意 Iterator<E>
定义 E next()
, 所以你不需要转换为 String
在这种情况下。
另一个说明性的例子
这是来自 Java Language Guide/For-each loop 的示例:
Here is a common mistake people make when they are trying to do nested iteration over two collections:
List suits = ...; List ranks = ...; List sortedDeck = new ArrayList(); // BROKEN - throws NoSuchElementException! for (Iterator i = suits.iterator(); i.hasNext(); ) for (Iterator j = ranks.iterator(); j.hasNext(); ) sortedDeck.add(new Card(i.next(), j.next()));
Can you spot the bug? Don't feel bad if you can't. Many expert programmers have made this mistake at one time or another. The problem is that the
next
method is being called too many times on the “outer” collection (suits). It is being called in the inner loop for both the outer and inner collections, which is wrong. In order to fix it, you have to add a variable in the scope of the outer loop to hold the suit:// Fixed, though a bit ugly for (Iterator i = suits.iterator(); i.hasNext(); ) { Suit suit = (Suit) i.next(); for (Iterator j = ranks.iterator(); j.hasNext(); ) sortedDeck.add(new Card(suit, j.next())); }
So what does all this have to do with the for-each construct? It is tailor-made for nested iteration! Feast your eyes:
for (Suit suit : suits) for (Rank rank : ranks) sortedDeck.add(new Card(suit, rank));
有 JSONObject.keys()
是Iterable
而不是 Iterator
,然后 for-each 是您情况下的最佳解决方案。如果你认为提高可读性是值得的,你可以,例如添加keys
进入 Collection<String>
,这是一个 Iterable
.
相关问题
关于java - 将字符串解析为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3227055/