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

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.

Related

Java `json_decode` (PHP) equivalent

I'm coming to Java from a PHP background, and am surprised to see that JSON to object conversion is so constrained. In all the Jackson tutorials I came across, it looks like the object to be read needs to be pre-defined. Thus, if my data is in, say, JSON API format, I need to write boilerplate code to strip out everything except the "data" part, and then somehow convert all the strings into objects one by one.
I really miss PHP's json_decode function, which will read any JSON and give you a PHP object to play with. It also builds the necessary structure into the object, adding arrays and sub-objects as needed. Of course I understand that Java is a compiled language, but I'm wondering how this can be made easier.
As a strongly typed language Java often has less of these "just give it to me"-type of functionalities, but that doesn't mean they don't exist. Even Jackson can deserialize JSON without a predefined schema, giving you Maps and Lists instead of domain objects.
Just remember that if you're working on "real" projects, there are plenty of advantages from having the schemas defined. They weren't invented to annoy you, but to make sure that you can trust your data being in the correct form (or find out early if it's not).

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

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

Java: Ways to parse XML in E4X?

I was wondering if there was a way to parse XML using E4X, or something similar to E4X.
Does such a framework / library exist?
Thanks!
You can use JavaScript engine Rahino with Java which can handle E4X.
http://blogs.oracle.com/sundararajan/entry/desktop_scripting_applications_with_netbeans
http://www.ibm.com/developerworks/library/ws-ajax1/
Java cannot support dynamically defined members, as JavaScript can.
However, with design-time generation, you can get Java whose members reflect the XML. E.g., JAXB
E4X is a language extension, XML is treated like a primitive. E4X is not just for parsing XML, it's using XML as real types.
This can't be simulated or done with a Java 'framework', it would require a language extension for Java.
There is no parsing XML with E4X. It is a specification that makes XML a native data type. Among browsers, only Firefox supports it as of now.
Here's a list of all known implementations of the spec.
A framework can only mimic making XML access easier, but will not fundamentally change the way we use XML. For example, the SimpleXML extension in PHP simplifies things a lot, but under the hood it converts elements to objects using reflection.
So to have something like E4X, it has to be implemented in the language itself and there is no other non-ECMAScript based language that has this as of now.

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