While there are many frameworks for parsing JSON structured data, I was looking for a framework which will provide a generic object. I was expecting a returned object to be more like a property holder (no Hashmaps, please). I came across GSON and found it is the perfect candidate for what I am looking for.
But my problem was not addressed completely, I was looking for embedding GSON inside CXF as JAX-RS provider. The default implementation which comes with CXF, was returning a concrete object which was impossible for me to build and make available to the provider. Hence, I needed a way to configure GSON as JAX-RS provider and capitalize the features which I was more interested in.
This led the way to build my own JAX-RS provider using GSON. Fortunately, it is much easier with CXF to create JAX-RS provider and plug it in the framework.
Create a class “GSONJAXRSProvider” and implement
Override the method to parse incoming data.
public Object readFrom(Class object, Type arg1, Annotation annotations, MediaType mediaType, MultivaluedMap httpHeaders, InputStream inputStream) throws IOException, WebApplicationException
I have used following code to deserialize data
InputStreamReader streamReader = new InputStreamReader(inputStream); JsonElement jsonObject = parser.parse(streamReader); return (Object)jsonObject;
Override the method to serialize outgoing data.
public void writeTo(Object object, Class arg1, Type arg2, Annotation annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream responseStream) throws IOException, WebApplicationException
And here goes code for serializing JSONObject to string.
PrintWriter printWriter = new PrintWriter(responseStream); JsonObject json = (JsonObject)object; printWriter.write(json.toString()); printWriter.flush();
Configure the newly created class as JAX-RS provider in CXF. Refer following configuration snippet.