0

我有几个模型对象正在使用构建器模式,我试图通过 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);
    }
  }
  ...
}

春季 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());
  }
}
4

1 回答 1

1

您错过@ResponseBody了控制器处理程序方法。

于 2013-05-20T16:49:48.280 回答