【发布时间】:2021-01-12 13:41:34
【问题描述】:
我正在使用第三方 API 以 JSON 格式的 Map
现在一种方法是遍历 Map 并使用反射来填充 POJO。
我想知道 Jackson / Gson API 是否可用于填充 POJO。我都试过了,但是 POJO 中没有填充值。
JSON:
{
"Id": [
"345"
],
"Name": [
"John"
]
}
POJO:
public class Employee implements Serializable {
private String id;
private String name;
// getter / setter
}
My Code:
Map<String, Set<?>> data = someObject.getDataSet();
ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Employee employee = mapper.convertValue(data, Employee.class);
System.out.println(employee);
更新: 我试过了,但 POJO 仍然是空的
Map<String, Set<?>> data = someObject.getDataSet();
Map<String, String> map = data.entrySet().stream()
.filter(entry -> entry.getValue() != null)
.collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue().iterator().next().toString()));
Employee employee = null;
ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Employee = mapper.convertValue(map, Employee.class);
System.out.println(employee);
Gson gson = new Gson();
JsonElement jsonElement = gson.toJsonTree(map);
Employee = gson.fromJson(jsonElement, Employee.class);
System.out.println(employee);
【问题讨论】:
-
[ "345" ] 表示它是一个数组,所以你可以改变String id;列出
id -
@NehaK 这个问题表明他想单独保存它,而不是在一个列表中
-
@PiotrŻmudzin 你是对的。即使值是数组,我也想填充 POJO。
标签: java json jackson gson jackson-databind