Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson2 custom deserializer factory

Tags:

jackson

I am porting jackson 1.6 code to jackson 2 and stumbled upon a deprecated code.

What i did in jackson 1.6 is:

CustomDeserializerFactory sf = new CustomDeserializerFactory();
mapper.setDeserializerProvider(new StdDeserializerProvider(sf));
sf.addSpecificMapping(BigDecimal.class, new BigDecimalDeserializer());
t = mapper.readValue(ts, X[].class);

Anyone knows how to do it in jackson 2?

like image 575
timoffei Avatar asked Apr 12 '12 16:04

timoffei


People also ask

What is Jackson deserializer?

Jackson is a powerful and efficient Java library that handles the serialization and deserialization of Java objects and their JSON representations. It's one of the most widely used libraries for this task, and runs under the hood of many other frameworks.


2 Answers

To add a factory--not just a deserializer--don't use SimpleModule. Create your own Module and within it create a Deserializers object that is added to the SetUpContext. The Deserializers object will have access to similar methods that the factory did where you can get extra type information about the deserializer needed.

It will look something like this (note that it doesn't need to be an inner class):

public class MyCustomCollectionModule extends Module {

@Override
public void setupModule(final SetupContext context) {
    context.addDeserializers(new MyCustomCollectionDeserializers());
}

private static class MyCustomCollectionDeserializers implements Deserializers {

    ... 

    @Override
    public JsonDeserializer<?> findCollectionDeserializer(final CollectionType type, final DeserializationConfig config, final BeanDescription beanDesc, final TypeDeserializer elementTypeDeserializer, final JsonDeserializer<?> elementDeserializer) throws JsonMappingException {

        if (MyCustomCollection.class.equals(type.getRawClass())) {
            return new MyCustomCollectionDeserializer(type);
        }
        return null;
    }

    ...
}
}
like image 113
ryber Avatar answered Jan 02 '23 22:01

ryber


In Jackson 2.0:

  1. Create a Module (usually SimpleModule)
  2. Register custom handlers with it.
  3. Call ObjectMapper.registerModule(module);.

This is available on Jackson 1.x as well (since 1.8 or so).

like image 42
StaxMan Avatar answered Jan 02 '23 21:01

StaxMan