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.

vatsal mevada
  • 5,148
  • 7
  • 39
  • 68
ammy
  • 306
  • 1
  • 6
  • 23
  • 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>, 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. – Hasanuzzaman Rana Jun 21 '19 at 05:42
  • For reference you could check - https://www.mkyong.com/java/json-simple-example-read-and-write-json/ , https://www.codota.com/code/java/methods/org.json.simple.parser.JSONParser/parse – Hasanuzzaman Rana Jun 21 '19 at 05:47

1 Answers1

4

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!

entpnerd
  • 10,049
  • 8
  • 47
  • 68
  • 2
    also keep in mind that FileReader blocks the eventqueue, therefore vertx has own filesystem tools: vertx.fileSystem().readFile(...) – taygetos Jun 21 '19 at 07:36