Skip to content

JSON Serialization

DuyHai DOAN edited this page Aug 25, 2017 · 15 revisions

Default configuration

It is possible to tell Achilles to serialize any unsupported data type into an JSON string using the @JSON annotation.

    //Simple value encoding
    @Column
    @JSON
    private MyPOJO pojoAsJson;
    
    //Collection value encoding
    @Column
    private List<@JSON MyPOJO> myPojosAsJson;
    
    //Map key encoding
    @Column
    private Map<@JSON MyPOJO, String> mapKeyEncoding;
        
    //Map value encoding
    @Column
    private Map<Integer, @JSONMyPOJO> mapValueEncoding;
 

JSON serialization is way faster than the old plain Object serialization since only data are serialized, not class structure.

By default, Achilles sets up an internal Object Mapper with the following feature config:

  1. MapperFeature.SORT_PROPERTIES_ALPHABETICALLY = true
  2. SerializationInclusion = JsonInclude.Include.NON_NULL
  3. DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES = false
  4. AnnotationIntrospector pair : primary = JacksonAnnotationIntrospector, secondary = JaxbAnnotationIntrospector

Jackson will serialize all your entities even if they do not have any Jackson annotations. You can also use JAXB annotations.


Custom Object Mapper

It is possible to inject a pre-configured Jackson Object Mapper as configuration parameter to bootstrap the ManagerFactory class using the OBJECT_MAPPER parameter.

    Map<ConfigurationParameters,Object> configMap = new HashMap<>();
    configMap.put(JACKSON_MAPPER, preConfiguredObjectMapper);

    ...

Custom Jackson Mapper Factory

Last but not least, it is possible to further custom JSON serialization using the ObjectMapperFactory interface and setting the JACKSON_MAPPER_FACTORY parameter:

    public interface JacksonMapperFactory
    {
        public <T> ObjectMapper getMapper(Class<T> type);
    } 
    
    
    Map<ConfigurationParameters,Object> configMap = new HashMap<>();
    configMap.put(JACKSON_MAPPER_FACTORY, customJacksonMapperFactoryImpl);
    
    ...
    

When both JACKSON_MAPPER_FACTORY and JACKSON_MAPPER params are provided for configuration, Achilles will ignore the JACKSON_MAPPER param and only use the JACKSON_MAPPER_FACTORY one

Home

Clone this wiki locally