0

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"
}
omlfc be
  • 147
  • 2
  • 13

2 Answers2

0

I haven't tested it but as your json file has only one object, I prefer to use JSONObject instead of JSONArray:

    Object obj = parser.parse(new FileReader("comments.json"));
    JSONObject jsonObject = (JSONObject) obj;
    String name = (String) jsonObject.get("name");
    System.out.println(name);
void
  • 7,760
  • 3
  • 25
  • 43
0

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);
jseashell
  • 745
  • 9
  • 19