0

I have a json file SenderTest.json in my src/test/resources package of my project. I think my approach of deserializing the json object to java object is right.

JsonObject json = new JsonObject();
String jsonStrng = json.toString();

ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Animal animal = mapper.readValue(jsonStrng, Animal.class);

but I am struggling to understand how to get the SenderTest.json from recources package into this JsonObject

Georgi Michev
  • 764
  • 5
  • 18
  • 37
  • 1
    The json will only be available for the tests, as it's included in the test/resources directory. To read it you need to do getClass().getClassLoader().getResourceAsStream("SenderTest.json") and read the stream – Javi Mollá Sep 19 '18 at 12:42

2 Answers2

1

Try this.

Animal  animal = mapper.readValue(new FileInputStream(new File("SenderTest.json")), Animal.class);

Here we are passing the InputStream as the first parameter in the readValue method

Joel George
  • 62
  • 2
  • 12
0

If your question is "how do I read a file located within the project itself", it's been asked before - try out the following question for an example: Read file from a folder inside the project directory

If you're actually asking "how do I read the file without working through Object mapping and explicit deserialization", you can do the following:

new JSONObject( IOUtils.toString( new FileInputStream( path.toString() ), "UTF-8" ) );
bsplosion
  • 2,641
  • 27
  • 38