I'm using the com.google.gson.Gson
API to convert a JSON string to a Java object:
Gson gson = new Gson();
User u = gson.fromJson(jsonString, User.class);
I'd like to know if there's an equivalent API in javax.json api to do the equivalent. Thanks!
This is definitely not possible with an oneliner like as with Gson. The
javax.json
API is very low level. It only returns you a JSON object structure which you've to breakdown and map to a javabean further all by yourself.In order to achieve (nearly) the same effect as
Gson#fromJson()
, here's a kickoff example of the boilerplate code. Parameterized types and javabeans are supported to certain extent. It's all standard Java SE API, the javabeans are introspected with little help ofjava.beans
API.Usage:
In case you're seeing an
UnsupportedOperationException
coming from one ofdecodeXxx()
methods, just add the desired conversion logic to the method in question. Of course this could be refactored further to apply the strategy pattern and such so that it's flexible and extensible, but then we're basically reinventing Gson.No, there is not.
And before you try other parsers then GSON: org.json is buggy/has implementation mistakes. QuickJson is buggy/has implementation mistakes