我已经为此苦苦挣扎了一段时间。我正在将Spring MVC 3.1与Jackson MessageConverter一起用于JSON序列化,并希望配置其他序列化器。 我有一个ApiCustomer类
public class ApiCustomer {
//customer
private String id;
private int customerNr;
private String customerNrExternal;
private String status;
@Override
@Column(table=PREFIX_CUSTOMER, name="id")
public String getId() { return id; }
@Override
public void setId(String id) { this.id = id; }
@Column(table=PREFIX_CUSTOMER, name="customerNr")
public int getCustomerNr() { return customerNr; }
public void setCustomerNr(int customerNr) { this.customerNr = customerNr; }
@Column(table=PREFIX_CUSTOMER, name="customerNrExtern")
public String getCustomerNrExternal() { return customerNrExternal; }
public void setCustomerNrExternal(String customerNrExternal) { this.customerNrExternal = customerNrExternal; }
@Translate
@Column(table=PREFIX_PREDEFINED_PROPERTY, name="value")
public String getStatus() { return status; }
public void setStatus(String status) { this.status = status; }
}
我想序列化为JSON的。对于某些字段(在本示例中为status
),我想使用自定义序列化器TranslateSerializer
:
public class TranslateSerializer extends StdSerializer<String> {
public TranslateSerializer() {
super(String.class);
}
public TranslateSerializer(Class<String> t) {
super(t);
}
@Override
public void serialize(String value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
jgen.writeStartObject();
jgen.writeStringField("key", value);
jgen.writeStringField("translated", Strings.instance().get(value));
jgen.writeEndObject();
}
}
第一个问题:是否可以仅在@translate
中使用自己的注释,例如ApiCustomer
并配置spring,这样就不必使用@JsonSerialize(using = TranslateSerializer.class)
?
第二个问题:如何注册一个仅用于带注释方法的附加序列化器?我当前的配置如下:
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<property name="featuresToDisable">
<array>
<util:constant static-field="com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS" />
</array>
</property>
<property name="serializers">
<array>
<bean class="TranslateSerializer"/>
</array>
</property>
</bean>
</property>
</bean>
<bean class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
<property name="marshaller" ref="xstreamMarshaller" />
<property name="unmarshaller" ref="xstreamMarshaller" />
</bean>
</mvc:message-converters>
</mvc:annotation-driven>