【发布时间】:2021-12-14 15:20:07
【问题描述】:
在将响应转换为我的 DTO 之前,我可以看到它看起来像这样:
{
"name": "HalloweenBundle2021",
"pricing":
{
"VirtualCurrencyDto(physicalCurrency=EUR, coinId=null)":
{
"amount": 8.99,
"discountAmount": 0
},
"VirtualCurrencyDto(physicalCurrency=USD, coinId=null)":
{
"amount": 9.99,
"discountAmount": 0
}
}
}
这是正确的。
但是,在响应/实际转换之后,physicalCurrency 字段都为空,而 coinId 字段获得完整的地图值:
{
"name": "HalloweenBundle2021",
"pricing":
{
"VirtualCurrencyDto(physicalCurrency=null, coinId=VirtualCurrencyDto(physicalCurrency=EUR, coinId=null))":
{
"amount": 8.99,
"discountAmount": 0
},
"VirtualCurrencyDto(physicalCurrency=null, coinId=VirtualCurrencyDto(physicalCurrency=USD, coinId=null))":
{
"amount": 9.99,
"discountAmount": 0
}
}
}
到底发生了什么?
我的回复是:
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class FooDto implements Serializable {
private String name;
private Map<VirtualCurrencyDto, PriceDto> pricing = new LinkedHashMap<>();
}
问题的关键是:
@Data
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class VirtualCurrencyDto implements Serializable {
// both of these fields should not be present, only one or the other
private DTOCurrency physicalCurrency; // an external enum
private String coinId;
public VirtualCurrencyDto(DTOCurrency physicalCurrency) {
this.physicalCurrency = physicalCurrency;
}
public VirtualCurrencyDto(String coinId) {
this.coinId = coinId;
}
}
我的 objectMapper bean
@Bean
public ObjectMapper getObjectMapper() {
return new ObjectMapper()
.setSerializationInclusion(JsonInclude.Include.ALWAYS)
.registerModule(new JsonNullableModule());
}
并且正在通过MockMvc获取响应
public FooDto getFooDto(String name) throws Exception {
MvcResult result =
mockMvc.perform(
get("/foo/" + name))
.andExpect(status().isOk())
.andReturn();
return objectMapper.readValue(
result.getResponse().getContentAsString(), // this part is fine, when I look at the string value
FooDto.class); // issue here, upon conversion
}
我应该注意,在提出请求时也是如此,例如在请求到达我的控制器以获取PUT 之前,数据看起来很好,但是在控制器中接收到它后,数据就像上面一样搞砸了(来自GET 的响应)。
【问题讨论】:
标签: java spring jackson objectmapper