Custom JSON serialization using Jersey 2.x / MOXy

Im using Jersey 2.x with built-in MOXy conversion from JSON ↔ POJO inside the built-in Jetty 9.x server.

Is it possible to programmatically define a custom JSON (de) serialization procedure for certain types (for example, Joda DateTime) (without POJO annotations) - if so, how?

I currently have the following code to configure Jersey with my embedded Jetty server instance:

ResourceConfig resourceConfig = new ResourceConfig(); resourceConfig.packages( "com.company.app.rest.v1" ); resourceConfig.register( new GZipEncoder() ); resourceConfig.register( new LoggingFilter() ); ServletHolder servletHolder = new ServletHolder( new ServletContainer( resourceConfig ) ); context.addServlet( servletHolder, "/rest/v1/*" ); 

and its working mode for simple POJOs - I just want to be able to configure serialization (de). Is there a way to convert plugins for certain types line by line:

 registerTypeConverter( MySpecificType.class, CustomReader.class, CustomWriter.class ); 
+5
source share
1 answer

I think you might be interested in this wiki article . Most of them are related to XML serialization, but below you will learn how to configure JSON serialization.

Basically you create a custom ContextResolver<JAXBContext> that returns a custom JSONJAXBContext , which in turn has a custom JSONConfiguration . Do not forget to comment it with @Provider (and register it in your application, if necessary). I will copy the sample code for completeness, you never know how long these things survive :)

 @Provider public class JAXBContextResolver implements ContextResolver<JAXBContext> { private JAXBContext context; private Class[] types = { Address.class, Customer.class, CustomerResource.class }; public JAXBContextResolver() throws Exception { this.context = new JSONJAXBContext(JSONConfiguration.natural().build(), types); } public JAXBContext getContext(Class<?> objectType) { for (Class type : types) { if (type == objectType) { return context; } } return null; } } 
0
source

Source: https://habr.com/ru/post/1205290/


All Articles