java nashorn parse json from file - java

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

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

Related

Which one to use? JSONObject from org.json VS JsonObject from javax.json

This is my first post. As a budding Android developer, I read SO posts on a near daily basis on various topics, but for this question, I didn't find any help from Google or SO.
My research so far:
Searching for this question was harder than normal because the search engines don't seem to care about case-sensitivity, which is vital in this issue. Searching Google only gave me links to the classes themselves, old articles, or completely irrelevant articles. The closest I got was JSONArray vs JSONObject, and that is a completely different question. SO searching gave the same results. As far as I can tell, ALL pertinent posts on SO refer to JSONObject and not JsonObject.
Neither Oracle nor json.org documentation mentioned the other side, nor did the Android developer JSONObject page which uses the org.json library.
http://docs.oracle.com/javaee/7/api/javax/json/JsonObject.html
http://www.json.org/javadoc/org/json/JSONObject.html
I would have also posted a link to the Android reference page for JSONObject, but my rep as a newbie is too low.
History of problem(s):
I was reading about Json encoding and decoding from the Oracle page, and I tried copying and pasting into my AndriodStudio IDE, which immediately produced an error, for which it did not suggest an import statement like it normally does. I have come to learn that means the class is not part of the built-in libraries.
The problem was that the code I pasted in used JsonObject (which comes from javax.json library) and not JSONObject (which comes from org.json library). When I noticed the difference in case between the Android page and the Oracle page, I altered my code from Json to JSON and immediately my IDE offered the org.json import statement.
Question(s):
Why is an Oracle made class not part of the default libraries when an external library is?
Is JSON the old, deprecated way and Json the new, proper way?
Are they functionally identical? If not, please provide examples?
Are some situations better for one and some better for the other?
ULTIMATELY, which should I use, and why (if not already covered)?
If, javax.json, where is the best (safest) place to download that library)?
Bit late, but I wanted to share my opinion on this.
I faced this problem recently when I found a Java project with both libraries and they were used at the same time.
I think that org.json is easier to read and to use, for 2 main reasons (for my needs):
JsonObject is immutable. You can't add new key/value pairs to an already existing JsonObject (reference here: javax.json: Add new JsonNumber to existing JsonObject)
It takes a few lines to pretty print a JsonObject or JsonArray, while it only takes 1 line to do it with JSONObject or JSONArray. Example:
StringWriter sw = new StringWriter();
Map<String, Object> properties = new HashMap<>();
properties.put(JsonGenerator.PRETTY_PRINTING, true);
JsonWriterFactory writerFactory = Json.createWriterFactory(properties);
JsonWriter jsonWriter = writerFactory.createWriter(sw);
jsonWriter.writeObject(jsonObject); //JsonObject created before
jsonWriter.close();
String prettyPrintedJSON = sw.toString();
That is the code I use to get an indented JSON to write to a file. And with org.json I only need jsonObject.toString(4).
Another difference is the constructors. You will need a JsonObjectBuilder to create a JSON with javax.json. One step more that can be avoided.
I'm sure there are more differences (not sure if it's possible to create a JsonObject from a String) but these are my thoughts.
JSONObject, as mentioned, is provided by android's API. JsonObject is specifically used for Java EE development which is essentially for web applications and networking capabilities among other things.
The reason Android does not prepackage JsonObject from Oracle Java EE package is because alot of the things javax can do, are not allowed within android like accessing the internet without permission. This means importing the entire jars files of javax would conflict with Android.
If you plan to build your own backend with Java EE, I would highly suggest using JsonObject over JSONObject. On the other hand, if you know a prebuilt rest service or something similar that supports Android's JSON even better.
I recommend you to use Google's json-simple toolkit in order to work with JSON Objects. It provides useful functions and has no dependency on external libraries which turned out to be a huge problem during the development of Android apps.
To answer your question: If you don't want to use json-simple in you project you should use the JSONObject from org.json, because it's provided by the Android JDK. For further information see http://developer.android.com/reference/org/json/JSONObject.html.
org.json does not contain a parse class for parsing the JSON string. whileorg.json.simple contains a parse class.
org.json.JSONObject contains lots of getter methods to get directly as int, boolean, object, string, JSON Array, etc. org.json.simple.JSONObject does not contain specific methods, so you need to type cast every time while getting value of a particular key.
In simple words use org.json.simple.JSONObject for parsing alone and type cast it into org.json.JSONObject for further use inside the program.

Looking for standard library or technique to get pretty-printed representation of OBJECT for Java

In order to understand internals of some code or print dumps on errors I use pp-like functions in Python and Emacs lisp.
Now I come to to Java and look for standard library or tecnique to get pretty-printed representation of OBJECT for Java.
Seems that current Java specification allow introspection of Java object at runtime. But introspection may be not so powerful. m(Object o) can not be called with new Object [] arg?
NOTE I am NOT looking to source code beautifier! I am looking for runtime pretty print Java object dumping.
NOTE2 These questions similar but not exactly same:
What's the simplest way to print a Java array?
Best pretty-printing library for Java?
Java dump an object
You could use the ReflectionToStringBuilder from the Apache Commons Lang library.
Sample:
String dump = ReflectionToStringBuilder.toString(object);
As to your question:
m(Object o) can not be called with new Object [] arg?
Sure it can, arrays of Object is a subtype of Object.
For a quick and dirty solution to show the output of a Java object, you could use Jackson http://jackson.codehaus.org/ this will output the object in JSON.

Tutorials/FAQs/Samples/Basics for JSON

I am trying to create and parse JSON, and I get by with some samples found on Google/SO or trial-and-error. But I need some help with JSON basics, parsing, creating arrays inside JSON strings, and so on. I read about the JSONStringer and such, but I need information about parsing and creating complex JSON.
EDIT: I use Java.
Thanks.
First step typically is to look beyond bare-bones Java lib from org.json; other related questions therefore are, for example:
https://stackoverflow.com/questions/338586/a-better-java-json-library
https://stackoverflow.com/questions/1668862/good-json-java-library
The reason for this is that there is no point in worrying too much about low-level details; rather you usually want to operate either with Java collections (List, Maps, wrapper types) or with basic Java objects. Other libraries can offer such abstractions.
My personal favorite is Jackson, and its tutorial is found here.
which language-script?
for example, if you are using javaScript jQuery offers you few functions for json (http://api.jquery.com/jQuery.parseJSON/)..
There isn't much to it. You got objects, arrays and primitives such as string, number, boolean and null. The syntax can be picked up by googling JSON.
The handling of JSON is more down to frameworks and server - are you translating a server side domain model to JSON? What server technology?
Client side pretty much any decent framework has helper methods for parsing JSON to get around certain browser differences (native JSON parsing being one). Check out jQuery.getJSON.
You can learn about JSON here.
In the Java side, you should actually not be writing/parsing JSON yourself. That's only a lot of tedious work and a waste of effort since there are plenty of libraries for this. Just pick a library which is able to convert a complex Java object to a JSON string (and vice versa) in a single call. This way you can concentrate on writing clean Java code, not on fiddling with JSON syntax in plain Java strings.
See also:
Converting complex JSON to Java
How to use Ajax/JSON in JSP/Servlet

JSON, JS to Java and Vice Versa, and other languages

I want to use JSON to represent JS objects send them to a Java program, and vice versa.
I would also like to do this for other languages. C# to Java maybe?
What do I use to do this? (Not sure if it is refered to as serialization or data binding)
Edit:
Once a Java object is represented in JSON, does this mean that JavaScript can parse it and convert it to the corresponding JavaScript objects?
I would recommend using Gson for this. It has the advantage that it supports generics and nested beans very well and it is also fast enough. I've posted a Gson#fromJson() example which converts a fairly complex JSON string to Java here: Converting JSON to Java
The Gson#toJson() to convert any valid Javabean-like object to JSON is basically a piece of cake:
String json = new Gson().toJson(object);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
Edit: Once a Java object is represented in JSON, does this mean that JavaScript can parse it and convert it to the corresponding JavaScript objects?
Sure you can access them like a JS object. If you're new to using JSON in JS as well, then I can recomment this kickoff tutorial: http://www.hunlock.com/blogs/Mastering_JSON_%28_JavaScript_Object_Notation_%29
You could use Google Web Toolkit to share objects between javascript and Java. With GWT you write all your code in Java and then the GWT compiler will handle the serialization of the RPC calls from javascript to Java and vice vera.
If you mean over some sort connection (network, local pipe, etc), it would be called data serialization. You'd use a library to encode your objects. json.org has a list of libraries that can do what you want.
If you're writing a Java server with a JS front end, there's always GWT, too (I've never used, but heard great things about it)
To go from JSON to objects in Java, I've heard that json-simple works well. It maps the JSON to a Java Map, which can contain String, Numbers, Lists and other Maps. This is a little simpler than some other libraries, which map directly to Java objects that you need to create to represent the JSON.
For an exhaustive list of JSON libraries in most major languages including both Java and C#, check out json.org.
To serialize javascript objects for transmission to a server, I've used https://github.com/douglascrockford/JSON-js/blob/master/json2.js. Very nice and easy.
To get JSON data in and out of java, I found this library pretty straightforward:
http://json-lib.sourceforge.net/
Creating javascript objects from JSON is a non-issue. JSON is valid javascript. You can simply run eval on it, or use a javascript library, which may offer some built-in security, which eval doesn't have.

Unserialize in Java a serialized php object

Does anyone know if it is possible, actually if it has been done, to serialize an object in php and unserialize it in Java (java-php communication). Maybe an adapter will be needed.
What do you think?
Thanks
There is serialized-php-parser, which is a Java implementation that can parse php-serialized objects. In general, if you have the choice, I wouldn't recommend php-serialized as an exchange format, because it isn't ascii-safe (It contains null-bytes). Go with a format like xml or json instead. If you need a bit of type-information, xmlrpc is a good choice. It has good implementations for both php and Java.
PHP and Java both use their own (obviously different) serialization schemes. You could however use an interchange format both could read and write.
The two most obvious examples are XML and JSON.
There are others however such as Google Protocol Buffers.
Another Java project to work with the PHP serialization format is Pherialize.
Let's say you are serializing an array like this:
array(3) {
[0]=>
string(8) "A string"
[1]=>
int(12345)
[2]=>
bool(true)
}
Then you can unserialize it in Java with Pherialize like this:
MixedArray list = Pherialize.unserialize(data).toArray();
System.out.println("Item 1: " + list.getString(0));
System.out.println("Item 2: " + list.getInteger(1));
System.out.println("Item 3: " + list.getBoolean(2));
Theoretically, it's certainly possible. It's just bytes after all, and they can be parsed. Of course, the deserialized object would contain only data, not any of the PHP methods. If you want that, you'd have to rewrite the behaviour as Java classes that correspond directly with the PHP classes.
In practice, the main problem seems to be that the PHP serialization format does not seem to be formally specified - at least there is no link to a specification in the manual.
So you might have to dig through the code to understand the format.
All in all, it sounds like it would be much easier and more stable to use something like XML serialization - I'm sure both languages have libraries that faciliate this.
The JSON format would be a good place to start. There are implementations for Java, PHP and many other languages.
While initially based on the javascript object literal notation,
JSON proved convenient for lightweight data transfer between all types of systems.
add into pom.xml
<dependency>
<groupId>de.ailis.pherialize</groupId>
<artifactId>pherialize</artifactId>
<version>1.2.1</version>
</dependency>
then in code use
MixedArray list = Pherialize.unserialize(data).toArray(); // data is string `enter code here`
You can somehow make use of PHP's var_export() function for this, which returns a parseable string representation of the object you want to serialize.
I remember a snippet for Drupal (PHP CMS) where this functionality was needed. Just found it, so take a look at Serialized drupal node objects to java (should work with any PHP serialized object).
Maybe you can use that. I don't know whether there are issues with newer versions of PHP.
Serializing an object in PHP will dump the object properties. The resulting string isn't terribly complicated.
echo serialize(
array(1, null, "mystring", array("key"=>"value"))
);
Results in:
a:4:{i:0;i:1;i:1;N;i:2;s:8:"mystring";i:3;a:1:{s:3:"key";s:5:"value";}}
The string identifies datatypes, array lengths, array indexes and values, string lengths... Wouldn't take too much effort to reverse-engineer it and come up with your own parser, I think.
Like previous answers have mentioned, I would avoid PHP object serialization if possible. Use JSON (which is actually faster than serialize() in PHP), thrift or some other format that is more universal.
If you have no choice I have been working on a Jackson Module to enable reading and writing serialized PHP from Java. Jackson is a great JSON parser and since PHP serialization format is pretty similar it seemed like a good fit. It's not quite complete yet (writing is still a work in progress).
A better choice is to parse php serialized string to JSONArray, this repo (https://github.com/superalsrk/PhpSerialization) may help you
Note that there's a Java implementation of PHP. So you may be able to serialise the object and pass it to your Java-PHP instance, deserialise and then call into your Java infrastructure.
It all sounds a bit of an unholy mess, but perhaps worth looking at!
Use Web Services (REST, RPC, SOAP) or any other solution storing plain text that will allow you to read/rebuild the data from Java.
You may be also interested in using PHP/Java bridge (http://php-java-bridge.sourceforge.net/). It has own protocol. In their site said that it's fast implementation of bridge.
Try xstream (converts Java objects into readable XML) to serialize and then write your own PHP code to deserialize.

Categories