How to read a JSON file that is inside a package?

Asked

Viewed 3,372 times

2

I need to file a case file *.JSON. I understand that there is a library for this in case I use the json-simple-1.1.1. How it is necessary to read the file first and then work with it.

My question is this::

I keep the file file.json within a package com.app.json and I need to access this file.

What would be the most efficient method to access this file within the package?

Observing:

That should be good for files .json, .txt, .xml and others.

1 answer

2


It seems to me that the package where the files will be will always be the same. This way, just use the code below:

Reader in = new InputStreamReader(getClass().getResourceAsStream("/com/app/json/file.json") );
Object o = JSONValue.parse(in);

Otherwise, you can write a function that receives the package name and turns to a valid path within the classpath.

Hugs

  • Thank you. Why are you using "Object o = Jsonvalue.parse(in);" as an example? I am using the following line: Jsonobject jsonObjeto = (Jsonobject) parser.parse(in);

  • Exactly Eduardo, it’s just an example. You can use JSONObject if you prefer. Note also that it is not mandatory to use the class JSONValue, you can use JSONParser also.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.