java - 为 json 字符串创建 JSON 对象 Pojo
问题描述
我有这样的场景,需要使用对象映射器将其转换为对象。因此,我创建了一个如下所示的属性来捕获 OrderDispatchItemDTO。
@JsonProperty("OrderDispatchItemDTO")
private OrderDispatchItemDTO orderDispatchItemsDTO;
{
"Message": {
"MessageData": {
"OrderDispatchDTO": {
"StartDateTime": "2017-05-19T02:45:00",
"Details": {
"OrderDispatchItemDTO": {
more json properties
}
},
"EndDateTime": "2017-05-19T05:45:00",
}
},
"StatusID": 1,
}
}
但是如果 OrderDispatchItemDTO 作为列表出现,那么我的映射器将失败,因为它无法解析 json 字符串
@JsonProperty("OrderDispatchItemDTO")
private List<OrderDispatchItemDTO> orderDispatchItemsDTO;
{
"Message": {
"MessageData": {
"OrderDispatchDTO": {
"StartDateTime": "2017-05-19T02:45:00",
"Details": [
"OrderDispatchItemDTO": {
more json properties
},
"OrderDispatchItemDTO": {
more json properties
}
],
"EndDateTime": "2017-05-19T05:45:00",
}
},
"StatusID": 1,
}
}
修复是 mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
解决方案
您可以使用 @JsonAnySetter 属性并动态设置您的列表。这是一个例子。在我的情况下,一个属性可以是数字或对象,所以这是我简单地解决它的方法:
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
try {
if (name.equals("property") && value != null) {
MyObject t = null;
if (value instanceof Long) {
t = new MyObject();
t.setId((Long) value);
} else if (value instanceof LinkedHashMap) {
t = mapper.convertValue(value, MyObject.class);
}
//putting t anywhere i.e. setting property
}
}
catch (Exception e) {
e.printStackTrace();
}
}
推荐阅读
- ksqldb - 是否有任何用于 ksqldb 查询的版本控制工具?
- vhdl - vhdl 无效的内存访问(悬空访问或堆栈大小太小)
- c# - C# 将 Web Core App 发布到 Azure 的外部登录问题(Google Api)
- php - 在循环中将元素添加到 PHP 关联数组
- azure - 即使没有更改,也可以从 blob 复制文件的逻辑应用
- powershell - 使用 ARM 或 PowerShell 在 AppService 中启用 .NET Core 集合
- java - 片段内的按钮与下一个片段的按钮重叠
- python - 如何使用单个 API 在 django/DRF 中为整个数据库创建搜索功能?
- xamarin.forms - 如何延迟两个信号之一但在必要时丢弃它?
- react-native - 如何在 API 中显示产品名称?