Search code examples
javajsonjson-simple

I'm trying to read a json file, but compiler says, Parser cannot be resolved JAVA


I've downloaded and added a json-simple.jar to my project in eclipse. The only problem is with the Parser, Eclipse says "parser cannot be resolved". While the JSONObject and JSONArray are working just fine.

I get the error when trying to read the file :

JSONParser parser = new JSONParser();
JSONArray jArray = (JSONArray) parser.parse(new FileReader("comments.json"));

imported as follows :

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

I've just started using json, so i might be missing something.

The comments.json file is of this format :

{
"postId": 1,
"id": 1,
"name": "id labore ex et quam laborum",
"email": "Eliseo@gardner.biz",
"body": "laudantium enim quasi est"
}

Solution

  • I personally prefer the Jackson library so I'm not as familiar with JSON.simple. Did you consider creating a ContainerFactory() for the parser? http://juliusdavies.ca/json-simple-1.1.1-javadocs/org/json/simple/parser/ContainerFactory.html

    Also, your "comment.json" is just a JSONObject(), so no need in giving in the extra overhead of JSONArray()

    Maybe give this a shot:

    ContainerFactory cf = new ContainerFactory();
    Map jsonContainer = cf.createObjectContainer(); 
    
    JSONParser parser = new JSONParser();
    JSONObject jObj = (JSONObject) parser.parse(new FileReader("comments.json"), jsonContainer);