2012-04-12 7 views
5

Estoy portando el código de jackson 1.6 a jackson 2 y tropecé con un código obsoleto.Jackson2 deserializador personalizado fábrica

lo que hice en Jackson 1.6 es:

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

Cualquiera sabe cómo hacerlo en Jackson 2?

Respuesta

1

en Jackson 2.0:

  1. Crear un Module (por lo general SimpleModule)
  2. manipuladores de Registro personalizados con él.
  3. Llamada ObjectMapper.registerModule(module);.

Esto también está disponible en Jackson 1.x (desde 1.8 o más).

0

Aquí es un ejemplo de registro de un módulo (en este caso Joda manejo de fechas) en Jackson 2.x:

ClientConfig clientConfig = new DefaultClientConfig(); 

    ObjectMapper mapper = new ObjectMapper(); 
    mapper.registerModule(new JodaModule()); 
    mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); 

    JacksonJsonProvider provider = new JacksonJsonProvider(); 
    provider.configure(SerializationFeature.INDENT_OUTPUT, true); 
    provider.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); 

    provider.setMapper(mapper); 
    clientConfig.getSingletons().add(provider); 

    Client client = Client.create(clientConfig); 
1

Para añadir una fábrica - no sólo un deserializer - ¡No uso SimpleModule . Cree su propio Module y dentro de él cree un objeto Deserializers que se agrega al SetUpContext. El objeto Deserializers tendrá acceso a métodos similares que hizo la fábrica donde puede obtener información adicional sobre el deserializador necesario.

Se verá algo como esto (tenga en cuenta que no tiene por qué ser una clase interna):

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; 
    } 

    ... 
} 
} 
+0

¿Podría explicar * por qué * no utilizar SimpleModule? – foo

0

Exemplifying @StaxMan answer

Básicamente es necesario crear un módulo (SimpleModule), añadir una deserializer y registrar este módulo

final SimpleModule sm = new SimpleModule(); 
     sm.addDeserializer(Date.class, new JsonDeserializer<Date>(){ 

      @Override 
      public Date deserialize(JsonParser p, DeserializationContext ctxt) 
        throws IOException { 
       try { 
        System.out.println("from my custom deserializer!!!!!!"); 
        return new SimpleDateFormat("yyyy-MM-dd").parse(p.getValueAsString()); 
       } catch (ParseException e) { 
        System.err.println("aw, it fails: " + e.getMessage()); 
        throw new IOException(e.getMessage()); 
       } 
      } 
     }); 

     final CreationBean bean = JsonUtils.getMapper() 
       .registerModule(sm) 
//    .setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")) 
       .readValue("{\"dateCreation\": \"1995-07-19\"}", CreationBean.class); 

Aquí un ejemplo totalmente

import java.io.IOException; 
import java.text.ParseException; 
import java.text.SimpleDateFormat; 
import java.util.Date; 

import com.fasterxml.jackson.core.JsonParser; 
import com.fasterxml.jackson.databind.DeserializationContext; 
import com.fasterxml.jackson.databind.JsonDeserializer; 
import com.fasterxml.jackson.databind.module.SimpleModule; 

/** 
* @author elvis 
* @version $Revision: $<br/> 
*   $Id: $ 
* @since 8/22/16 8:38 PM 
*/ 
public class JackCustomDeserializer { 

    public static void main(String[] args) throws IOException { 

     final SimpleModule sm = new SimpleModule(); 
     sm.addDeserializer(Date.class, new JsonDeserializer<Date>(){ 

      @Override 
      public Date deserialize(JsonParser p, DeserializationContext ctxt) 
        throws IOException { 
       try { 
        System.out.println("from my custom deserializer!!!!!!"); 
        return new SimpleDateFormat("yyyy-MM-dd").parse(p.getValueAsString()); 
       } catch (ParseException e) { 
        System.err.println("aw, it fails: " + e.getMessage()); 
        throw new IOException(e.getMessage()); 
       } 
      } 
     }); 

     final CreationBean bean = JsonUtils.getMapper() 
       .registerModule(sm) 
//    .setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")) 
       .readValue("{\"dateCreation\": \"1995-07-19\"}", CreationBean.class); 

     System.out.println("parsed bean: " + bean.dateCreation); 
    } 

    static class CreationBean { 
     public Date dateCreation; 
    } 

} 
Cuestiones relacionadas