gpt4 book ai didi

java - Jackson @JsonIgnoreType 不适用于静态内部类

转载 作者:行者123 更新时间:2023-12-01 14:33:45 28 4
gpt4 key购买 nike

我有几个使用构建器模式的模型对象,我试图通过 Spring MVC 用 Ja​​ckson 序列化它们。问题是,我不希望内部静态构建器类与外部类一起序列化。我尝试在各个 getter 方法上使用 @JsonIgnore,但最终得到一个空对象。我还尝试在内部类本身上使用 @JsonIgnoreType ,但这似乎没有任何效果。有人知道如何让 jackson 忽略静态内部类吗?提前致谢。

使用 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

@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());
}
}

最佳答案

您在 Controller 处理程序方法中错过了@ResponseBody

关于java - Jackson @JsonIgnoreType 不适用于静态内部类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16653444/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com