我试图从json对象解析数组列表,如下面的代码,
File file = new File(HomePage.jsonFilePath);
if(file.exists()) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader(file));
JSONObject jsonObject = (JSONObject) obj;
System.out.println("Customer json for config customer "+jsonObject.toString());
configuredBranch = (String) jsonObject.get("branch");
configuredSystem = (String) jsonObject.get("system");
expinContainerPath = (String) jsonObject.get("path");
if(isEditable) {
try {
JSONArray customerArray = (JSONArray) jsonObject.get("customer_list");
if(customerArray!=null && customerArray.size()>0) {
Iterator<String> iterator = customerArray.iterator();
while (iterator.hasNext()) {
System.out.println("customer gson"+iterator.next());
customerList.add(iterator.next());
}
}
}catch (Exception e) {
e.printStackTrace();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
执行此行时,控制台显示以下json System.out.println(&#34;客户json用于配置客户&#34; + jsonObject.toString());
{"path":"C:\\Users\\Documents","system":"Exp","customer_list":["test","test1"],"branch":"LRD"}
但是在迭代和打印时如下 System.out.println(&#34; customer gson&#34; + iterator.next()); 它始终打印测试,即customer_list中的第一项。我想在&#34; customer_list&#34;中显示所有项目。你能建议我这么做吗?提前致谢。
答案 0 :(得分:1)
您在next()
循环内调用迭代器的while
方法两次,而只调用它一次。所以,重写你的代码:
while (iterator.hasNext()) {
String customer = iterator.next();
System.out.println("Customer " + customer);
customerList.add(customer);
}