JSON to Java with JDK6
There are multiple frameworks for transforming a JSON expression to a Java object tree, but the Java Platform does not come out of the box with some
javax.json package (I heard there are plans for that).
Today I will show that you can easily transform a JSON expression to a simple Java object tree (map, arrays, primitive wrappers and string) with Java 6 and no additional framework.
Obviously, it may not be the best way to proceed, specially when it comes to speed, security or java mapping. However this solution is appropriate if those are not a concern and you don’t want to add a dependency to an external library for parsing JSON expressions.
The solution relies on the
toJava function that will return a Java version of the object:
Now you probably get the idea, each
Now we need to use the engine to convert JSON expressions:
Here there is a little trick: you can remark the usage of
AtomicReference and it may look inappropriate since we are not dealing with concurrent programming. The trick is that if we return a
Those three pieces together makes a lightweight solution to transform JSON expressions to Java objects. There are certainly corner case not handled in this code, but it’s a solid basis to start with, I saved the code in a GitHub gist there.
blog comments powered by Disqus