杰克逊定制解串器工厂

时间:2012-04-12 16:56:47

标签: jackson

我将杰克逊1.6代码移植到杰克逊2并偶然发现了一个弃用的代码。

我在杰克逊1.6中所做的是:

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

任何人都知道如何在杰克逊2中做到这一点?

4 个答案:

答案 0 :(得分:1)

杰克逊2.0:

  1. 创建Module(通常为SimpleModule
  2. 使用它注册自定义处理程序。
  3. 致电ObjectMapper.registerModule(module);
  4. 这也适用于Jackson 1.x(自1.8左右)。

答案 1 :(得分:1)

要添加工厂 - 而不仅仅是反序列化工具 - 请勿使用SimpleModule。创建您自己的Module,并在其中创建一个Deserializers对象,该对象已添加到SetUpContextDeserializers对象可以访问工厂所做的类似方法,您可以获得有关所需反序列化器的额外类型信息。

它看起来像这样(注意它不需要是一个内部类):

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

    ...
}
}

答案 2 :(得分:0)

以下是在Jackson 2.x中注册模块(在本例中为Joda日期处理)的示例:

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

答案 3 :(得分:0)

Exemplifying @StaxMan answer

基本上你需要创建一个模块(SimpleModule),添加一个反序列化器并注册这个模块

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

这是一个完整的例子

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

}