I'm trying to parse a json
file on my desktop using java
and intelliJ
. The googling I did seemed to bring up other JSON
/Java
API's and yet it seems nashorn
comes with intellij
, so I would rather try using that.
I can't figure it out however. I tried to adapt some code (JSONParser parser = new JSONParser();
) but there was an error with an empty JSONParser
declaration. How do I do it? I would like to save each json
object as a java object (it is a JSON
obj with 2 strings and an array and I'd like to preserve this structure).
Any help would be appreciated. I did look around but couldn't find the answer in a way that seemed applicable to this situation. Presumably I would still use FileReader
to open the file. I've been using BufferedReader
to read each line. Do I still use those with JSON
files?
Thanks, Rebecca
Nashorn
is not a JSON
parser. It's a Javascript
engine. If you want to parse JSON
strings with Java, there are several good libraries. Gson
and Jackson
are popular examples.
To parse a JSON
string into a Java object (deserialize), first you need to create the appropriate type
(Java class). You pass this type
as a parameter when you deserialize your JSON
.
For example, with Gson:
Gson gson = new Gson();
MyType myobject = gson.fromJson(jsonSource, MyType.class);