我有几个使用构建器模式的模型对象,我试图通过Spring MVC与Jackson序列化。问题是,我不希望内部静态构建器类与外部类一起序列化。我尝试在各个getter方法上使用@JsonIgnore,但我最终得到了一个空对象。我也尝试在内部类本身使用@JsonIgnoreType,但这似乎没有任何影响。任何人都知道如何让杰克逊忽略一个静态的内部阶级?提前谢谢。
使用Spring 3.2.2和Jackson 2.2.1
包含构建器的简单类
public final class Address {
private final String street;
private final String city;
private final String state;
private Address(Address.Builder addressBuilder) {
street = addressBuilder.street;
city = addressBuilder.city;
state = addressBuilder.state;
}
public static Address.Builder newBuilder() {
return new Address.Builder();
}
@JsonIgnoreType // has no effect
public static final class Builder {
private String street;
private String city;
private String state;
private Builder() {}
public Builder street(String street) {
this.street = street;
return this;
}
...
// Java Beans setters/getters used by Spring
public void setStreet(String street) {
this.street = street;
}
public String getStreet() {
return street;
}
...
public Address build() {
return new Address(this);
}
}
...
}
Spring XML配置
<bean id="jacksonObjectMapper" class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<property name="failOnEmptyBeans" value="false" />
<property name="simpleDateFormat" value="MM/dd/yyyy" />
</bean>
...
<bean id="contentNegotiatingViewResolver" class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver" p:order="3">
<property name="defaultViews">
<bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView" p:objectMapper-ref="jacksonObjectMapper" p:extractValueFromSingleKeyModel="true" />
</property>
</bean>
序列化结果
{"builder":{"street":"1234 Some street"},"address":{"street":"1234 Some street","city":"Some City","state":"Some State"}}
预期结果
{"street":"1234 Some street","city":"Some City","state":"Some State"}
以下是用于返回Address对象的Spring控制器
@Controller
@Validated
@RequestMapping("/address")
public class AddressController extends AbstractController {
@Resource private AddressService addressService;
@RequestMapping("/clean")
public Address cleanAddress(@Validated({AddressGroup.Domestic.class}) Address.Builder address) {
return addressService.cleanAddress(address.build());
}
}
答案 0 :(得分:1)
您在控制器处理程序方法中错过了@ResponseBody
。