Json参数示例
{
"data": [
{
"name": "行号",
"type": "Integer",
"description": "行号"
}
]
}
转换为指定List<Entity>
private List<Entity> convertJsonToList(String requestData) {
ObjectMapper objectMapper = new ObjectMapper();
try {
String jsonData = objectMapper.readTree(requestData).get("data").toString();
List<Entity> list = objectMapper.readValue(jsonData, new TypeReference<List<Entity>>(){});
return list;
} catch (Exception e) {
return null;
}
}
引用 com.fasterxml.jackson
1. 创建 ObjectMapper 对象:ObjectMapper 是 Jackson 库中的一个类,用于处理 JSON 数据和 Java 对象之间的转换。
2. 尝试解析 JSON 数据:
- 使用 objectMapper.readTree(requestData) 解析传入的 JSON 字符串 requestData,得到一个 JsonNode 对象。
- 通过调用 .get("data") 方法,从这个 JsonNode 对象中提取出键为 "data" 的部分。这假设 requestData 字符串中包含一个 "data" 键,其值是我们需要的 JSON 数组。
- 调用 .toString() 方法将提取出的 JSON 数组转换为字符串 jsonData。
3. 将 JSON 数组字符串转换为对象列表:
- 使用 objectMapper.readValue(jsonData, new TypeReference<List<Entity>>(){}) 方法将 jsonData 字符串转换为 Entity类型的对象列表。这里使用了 TypeReference 来指定具体的泛型类型,因为 Java 的类型擦除机制不允许直接传递泛型类。