【问题标题】:Using Json-simple to parse an array of objects from a file使用 Json-simple 从文件中解析对象数组
【发布时间】:2017-08-11 21:38:27
【问题描述】:

我在使用 json-simple 解析 json 对象数组时遇到问题。

假设以下report 对象数组:

[
  {
    "title": "Test Object 1",
    "description": "complicated description...",
    "products": null,
    "formats": ["csv"]
  },
  {
    "title": "Test Object 2",
    "description": "foo bar baz",
    "products": ["foo"],
    "formats": ["csv", "pdf", "tsv", "txt", "xlsx"]
  },
  {
    "title": "Test Object 3",
    "description": "Lorem Ipsum stuff...",
    "products": null,
    "formats": ["pdf", "xlsx"]
  }
]

在以下代码中,从文件中读取后,我如何遍历数组中的每个对象来执行操作?

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import java.io.FileNotFoundException;
import java.io.FileReader;

public class JsonReader {

public static void main(String[] args) {

    JSONParser parser = new JSONParser();

    try {
        Object obj = parser.parse(new FileReader("sample.json"));

        //convert object to JSONObject
        JSONObject jsonObject = (JSONObject) obj;

        //reading the string
        String title = (String) jsonObject.get("title");
        String description = (String) jsonObject.get("description");

        //Reading an array
        JSONArray products = (JSONArray) jsonObject.get("products");
        JSONArray formats = (JSONArray) jsonObject.get("formats");

        //Log values
        System.out.println("title: " + title);
        System.out.println("description: " + description);

        if (products != null) {
            for (Object product : products) {
                System.out.println("\t" + product.toString());
            }
        } else {
            System.out.println("no products");
        }

        if (formats != null) {
            for (Object format : formats) {
                System.out.println("\t" + format.toString());
            }
        } else {
            System.out.println("no formats");
        }

    } catch (FileNotFoundException fe) {
        fe.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
}

运行调试器,似乎 jsonObject 正在存储数组,但我不确定如何获取它。为每个循环创建一个似乎不起作用,因为 JSONObject 不可迭代。

【问题讨论】:

  • 看来您要解析的 JSON 是 JSONArray,而不是单个 JSONObject。如果有帮助的话。

标签: java json json-simple


【解决方案1】:

您可以将 json 文件解析为 JSONArray 而不是 JSONObject

Object obj = parser.parse(new FileReader("sample.json"));

// convert object to JSONArray
JSONArray jsonArray = (JSONArray ) obj;

然后就可以遍历jsonArray了。

jsonArray.forEach(item -> {
    System.out.println(item);
    // Do stuff
});

【讨论】:

    【解决方案2】:

    我认为您的 JSON 在 JSON 标准方面无效(请参阅 JSON.org)。 JSON 应以“{”开头并以“}”结尾。我认为该数组无法以标准方式访问,因为它缺少密钥。如果可能的话,你应该把你的 JSON 放在中间(或者只是将它连接到你的代码中的 JSON 字符串):

    { "array": 
        //yourJson 
    }
    

    然后你可以使用类似的东西来访问数组:

    JSONArray array = (JSONArray) jsonObject.get("array");
    Iterator iter = array.iterator();
    
    
    while (iter.hasNext()) {
            System.out.println( ( iter.next() ).get("title") );
        }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-02
    • 1970-01-01
    • 2021-12-15
    • 1970-01-01
    • 2016-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多