0

是否存在任何方式如何为使用 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>
4

1 回答 1

2

是的,您可以查看自定义反序列化器

ObjectMapper mapper = new ObjectMapper();
SimpleModule testModule = new SimpleModule("MyModule", new Version(1, 0, 0, null))
   .addDeserializer(IdentifiableEntity.class, new IdentifiableDeserializer());
mapper.registerModule(testModule);
于 2015-07-20T10:02:46.737 回答