如何为实现给定接口

时间:2015-07-20 09:51:34

标签: java json spring jackson fasterxml

如果使用Jackson 2.X和Spring Framework为所有实现特定接口的类型注册JSON反序列化器,而不是使用@JsonDeserialize(using = IdentifiableDeserializer.class)注释每个属性,是否存在任何方式?

通用反序列化程序

public class IdentifiableDeserializer extends JsonDeserializer<IdentifiableEntity> implements ContextualDeserializer{

    @Override
    public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property)
            throws JsonMappingException {
        // ...
    }

    @Override
    public IdentifiableEntity deserialize(JsonParser jp, DeserializationContext ctxt)throws IOException, JsonProcessingException {
        // ...
    }

}

应反序列化的实体

public class MyEntity implements IdentifiableEntity{
    private Long id;

    public getId(){
        return id;
    }
    //...
}

贡献莫过于

@Service("myEntityService")
private MyEntityService implements IdentifiableService<MyEntity>{

    MyEntity findById(Long id){
        //...
    }

}

我尝试了以下方法,但它不起作用。

<bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView">
    <property name="objectMapper">
        <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
            <property name="deserializersByType">
                <map key-type="java.lang.Class">
                    <entry key="xx.yy.IdentifiableEntity">
                        <bean class="xxx.yyy.IdentifiableDeserializer" />
                    </entry>
                </map>
            </property>
        </bean>
    </property>
</bean>

1 个答案:

答案 0 :(得分:2)

是的,您可以查看custom deserializers

ObjectMapper mapper = new ObjectMapper();
SimpleModule testModule = new SimpleModule("MyModule", new Version(1, 0, 0, null))
   .addDeserializer(IdentifiableEntity.class, new IdentifiableDeserializer());
mapper.registerModule(testModule);