marsupials
marsupials

Reputation: 81

java nashorn parse json from file

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

Upvotes: 3

Views: 8107

Answers (2)

Werlious
Werlious

Reputation: 594

To provide a more relevant answer than "use something else", the Nashorn runtime has JSON.parse and JSON.stringify just like nodejs. So, load the file in java (since you will have to load the file using java classes in nashorn anyway), and once you have a string representation of your file, call it script, and an instance of ScriptEngine, call it engine, just call eval and get the result like so: Object parsed = engine.eval("JSON.parse("+script+")";) and parsed will contain the parsed json, since eval returns the result of the last expression

This is only as useful as a Anonymous Object however, and will need to be handled in Java. You can also parse the json in nashorn and create a java object in nashorn (or just handle the data in nashorn), but this will require you to write a nashorn script.

Good Luck!

Reference:

ScriptEngine JavaDoc

A good nashorn tutorial

Reading a file in Java

Upvotes: 2

Amila
Amila

Reputation: 5213

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);

Upvotes: 2

Related Questions