4

I want to read .json file in java and typecast it to JsonObject.Please suggest the code with Json but not JSON.I am using io.vertx.core.json.JsonObject library .

Object obj = parser.parse(new FileReader()); //this is from library simple.ore.JSON.
JsonObject obj1;
obj1 = (JsonObject)(obj);

I tried to use JSONparser for file reader which gives JSONObject but i need JsonObject.

java.lang.ClassCastException: org.json.simple.JSONObject cannot be cast to io.vertx.core.json.JsonObject.

2
  • See, you need to use either org.json.simple.JSONObject or io.vertx.core.json.JsonObject. both provider are different and on the other hand, class JsonObject extends Object implements Iterable<Map.Entry<String,Object>>, io.vertx.core.shareddata.impl.ClusterSerializable, Shareable and public class JSONObject extends java.util.HashMap implements java.util.Map, JSONAware, JSONStreamAware, so you could see the difference. Commented Jun 21, 2019 at 5:42
  • For reference you could check - mkyong.com/java/json-simple-example-read-and-write-json , codota.com/code/java/methods/org.json.simple.parser.JSONParser/… Commented Jun 21, 2019 at 5:47

1 Answer 1

5

The problem is that you're using the parser from another library and expecting to get an instance of io.vertx.core.json.JsonObject. Instead, read your file containing your JSON text into a Java string. Note that you can do this using the IOUtils.toString(Reader) method. Then, use the JsonObject's constructor. For example, you could just use something similar to the following code:

String jsonStr = IOUtils.toString(new FileReader(myFileName));
JsonObject jsonObj = new JsonObject(jsonStr);

Hope that helps!

Sign up to request clarification or add additional context in comments.

1 Comment

also keep in mind that FileReader blocks the eventqueue, therefore vertx has own filesystem tools: vertx.fileSystem().readFile(...)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.