我正在尝试读取 json 文件,但编译器说无法解析解析器 JAVA
I'm trying to read a json file, but compiler says, Parser cannot be resolved JAVA
我已经下载 json-simple.jar
并将其添加到我在 eclipse 中的项目中。唯一的问题是解析器,Eclipse 说 "parser cannot be resolved"
。虽然 JSONObject
和 JSONArray
工作正常。
我在尝试读取文件时遇到错误:
JSONParser parser = new JSONParser();
JSONArray jArray = (JSONArray) parser.parse(new FileReader("comments.json"));
导入如下:
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
我刚开始使用 json,所以我可能遗漏了一些东西。
comments.json
文件格式如下:
{
"postId": 1,
"id": 1,
"name": "id labore ex et quam laborum",
"email": "Eliseo@gardner.biz",
"body": "laudantium enim quasi est"
}
我还没有测试过,但是由于你的 json 文件只有一个对象,我更喜欢使用 JSONObject
而不是 JSONArray
:
Object obj = parser.parse(new FileReader("comments.json"));
JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("name");
System.out.println(name);
我个人更喜欢 Jackson 库,所以我不太熟悉 JSON.simple。您是否考虑过为解析器创建 ContainerFactory()
? http://juliusdavies.ca/json-simple-1.1.1-javadocs/org/json/simple/parser/ContainerFactory.html
此外,您的 "comment.json"
只是一个 JSONObject()
,因此无需付出 JSONArray()
的额外开销
也许试一试:
ContainerFactory cf = new ContainerFactory();
Map jsonContainer = cf.createObjectContainer();
JSONParser parser = new JSONParser();
JSONObject jObj = (JSONObject) parser.parse(new FileReader("comments.json"), jsonContainer);
我已经下载 json-simple.jar
并将其添加到我在 eclipse 中的项目中。唯一的问题是解析器,Eclipse 说 "parser cannot be resolved"
。虽然 JSONObject
和 JSONArray
工作正常。
我在尝试读取文件时遇到错误:
JSONParser parser = new JSONParser();
JSONArray jArray = (JSONArray) parser.parse(new FileReader("comments.json"));
导入如下:
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
我刚开始使用 json,所以我可能遗漏了一些东西。
comments.json
文件格式如下:
{
"postId": 1,
"id": 1,
"name": "id labore ex et quam laborum",
"email": "Eliseo@gardner.biz",
"body": "laudantium enim quasi est"
}
我还没有测试过,但是由于你的 json 文件只有一个对象,我更喜欢使用 JSONObject
而不是 JSONArray
:
Object obj = parser.parse(new FileReader("comments.json"));
JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("name");
System.out.println(name);
我个人更喜欢 Jackson 库,所以我不太熟悉 JSON.simple。您是否考虑过为解析器创建 ContainerFactory()
? http://juliusdavies.ca/json-simple-1.1.1-javadocs/org/json/simple/parser/ContainerFactory.html
此外,您的 "comment.json"
只是一个 JSONObject()
,因此无需付出 JSONArray()
也许试一试:
ContainerFactory cf = new ContainerFactory();
Map jsonContainer = cf.createObjectContainer();
JSONParser parser = new JSONParser();
JSONObject jObj = (JSONObject) parser.parse(new FileReader("comments.json"), jsonContainer);