我正在使用 Jackson ObjectMapper 将字符串转换为 Pojo。
我收到的消息:
{
"countryCode": "US",
"skuNumber": "TEST",
"itemTaxCd": "89999",
"lastModifiedBy": "xyz"
}
方法:
public void processImsProductTaxEvents(String event) {
try {
SkuMasterDTO message = objectMapper.readValue(event, SkuMasterDTO.class);
log.debug("Received message from IMS", message);
} catch (Exception e) {
log.error("Error in Object Mapper converting String to TaxCodeDTO", e);
}
}
现在 countryCode 在 CountryDTO 里面,在 SkuMasterDTO 里面定义为一个 Set
private Set<CountryDTO> countries = new HashSet<>();
CountryDTO 类
public class CountryDTO implements Serializable {
private static final long serialVersionUID = 1L;
@NotNull
@Size(max = 2)
private String countryCode;
我正在尝试将国家/地区代码设置为 而不更改输入 Json。有什么建议吗?
最佳答案
考虑使用 DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAYS
在您的 ObjectMapper
实例中。然后,您必须将 json 字段 countryCode
更改为 countries
或使用 将
并在 Set countries
标记为 json 属性 countryCode
@JsonPropertyString
参数中提供构造函数/工厂方法。这将使您的对象映射器按照您的要求运行。
关于java - 如何将对象映射到字符串中以使用 ObjectMapper 进行设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43101287/