java - 将迭代器从 JSONObject 重写为 JSONArray

标签 java json

我有一个 JSONObjects 迭代器,但不幸的是我从 JSON 数据中得到了一个 JSONArray

现在我想重写它。我对 Java 还很陌生。有人可以告诉我如何处理这个问题吗?

我使用 json.simple 库。

public class JSONIteratorAuthor implements Iterator <Author> {

   private Iterator<JSONObject> authors;

   public JSONIteratorAuthor(JSONObject jsonObject){

       this.authors = ((JSONArray) jsonObject.get("authors")).iterator();
   }

   @Override
   public boolean hasNext() {
       return this.authors.hasNext();
   }

   public Author next() {
       if(this.hasNext()){
           Author a = new Author(0, "", "");
           JSONObject authorNode = (JSONObject) authors.next();
           a.setFirstName((String) authorNode.get("first_name"));
           a.setLastName((String) authorNode.get("last_name"));
           return a;
       }
       else {
       return null;
       }
   }    
}

最佳答案

由于缺乏有关 JSON 数据结构的信息,我假设如下:

  1. 您有一个 JSONArray 对象来调用构造函数
  2. JSONArray 包含 JSONObject
  3. 这些 JSONObject 具有合适的键值对

在这种情况下,以下解决方案应该有效。它利用了 JSONArray 本身是可迭代的这一事实。

private Iterator<JSONObject> authors;

@SuppressWarnings("unchecked")
public JSONIteratorAuthor(JSONArray array){
   authors = array.iterator();
}

@Override
public boolean hasNext() {
   return authors.hasNext();
}

@Override
public Author next() {
   if (hasNext()) {
       Author a = new Author(0, "", "");
       JSONObject authorNode = authors.next();
       a.setFirstName((String) authorNode.get("first_name"));
       a.setLastName((String) authorNode.get("last_name"));
       return a;
   }
   else {
       return null;
   }
}

编辑:根据您的实际输入,解决方案很简单:该数组包含对象,其中包含其他数组。因此,要使上述代码正常工作,您必须执行以下操作(其中 parsedJson 是您从实际输入文件中获取的内容(如 dropbox 中发布的那样):

Iterator array = ((JSONArray) parsedJson).iterator();           
while (array.hasNext()) {
    JSONObject json = (JSONObject) array.next();
    JSONArray authors = (JSONArray)json.get("authors");
    JSONIteratorAuthor test = new JSONIteratorAuthor(authors);
    while (test.hasNext()) {
        System.out.println(test.next());
    }
}

关于java - 将迭代器从 JSONObject 重写为 JSONArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34897350/

相关文章:

java - 单击 JList 中的项目时如何切换它们?

java - 当两个类同名时的类命名约定

javascript - 如何从 PHP 文件中检索 JSON 数据?

javascript - 如何将现有的 rjs 转换为在 Rails 3 中使用 jQuery 和 json?

json - 如何在 json 序列化期间忽略 IdentityUser 中的属性

java - 在 Liferay 计划作业中创建 Assets 类别

Gson引起的java.lang.NoClassDefFoundError

java - 在 Java 中创建未定义的方法行为?

javascript - 如何在 JavaScript 中解析未知的 JSON 对象

javascript - Chrome 扩展使用 jQuery 获取本地 json