Saturday, July 2, 2016

Customizing JSON mapping in Play

Play implements JSON conversion on base of Jackson. Play's static API Json should be used for operating Json data.
For example:
// Convert from JSON:
MyClass person = Json.fromJson(json, MyClass.class);
// Convert back to JSON:
JsonNode jsonNode = Json.toJson(person);
The default JSON mapping may be changed by providing configuration to Jackon ObjectMapper.

Play manual suggests to configure ObjectMapper in a custom ApplicationLoader. This post shows a different method of ObjectMapper customization.

ObjectMapper configuration with startup module


1. Create a class StartupHandler and implement with it the desired ObjectMapper configuration. Annotate the class with @Singleton annotation:
 @Singleton  
 public class StartupHandler {  
       public StartupHandler() {  
           configureJson();
       }  
      private void configureJson() {  
           ObjectMapper mapper = new ObjectMapper();  
           mapper.setVisibility(PropertyAccessor.ALL, Visibility.ANY);  
           mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
           Json.setObjectMapper(mapper);  
     }       
 }
2. Create a module class OnStartupModule and register JsonStartupHandler to be injected:
 package modules;  
 import com.google.inject.AbstractModule;  
 public class OnStartupModule extends AbstractModule {  
      @Override  
      protected void configure() {  
           bind(StartupHandler.class).asEagerSingleton();            
      }  
 }  
3. Add the module into application.conf:
play.modules.enabled += "modules.OnStartupModule"

Note 1: If a startup module already exists, just add into its configure method a binding for JsonStartupHandler.
Note 2: You can name a startup module class just Module and locate it in the root package. In this case Play will load it automatically on a application startup. It is no need to add a module name into the application.conf.

See working code example on Git

No comments :

About the author

My Photo
I trust only simple code and believe that code should be handsome. This is not a matter of technology, but professional approach, consolidated after years of software development. I enjoy to cause things working and feel very happy, when I manage to solve a problem.
Back to Top