Java 使用 Jackson 库将 JSON 数组转换为 List 并提取特定属性值
Java 使用 Jackson 库将 JSON 数组转换为 List 并提取特定属性值
本文介绍如何使用 Jackson 库将 JSON 数组转换为 Java List,并提取指定属性(例如'temperature')的值。
示例 JSON 字符串:
{"properties":[{"name":"mode","value":null},{"name":"temperature","value":"47"},{"name":"windspeed","value":null},{"name":"powerstate","value":"on"}]}
代码示例:
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) throws Exception {
String jsonStr = "{"properties":[{"name":"mode","value":null},{"name":"temperature","value":"47"},{"name":"windspeed","value":null},{"name":"powerstate","value":"on"}]}";
ObjectMapper mapper = new ObjectMapper();
Weather weather = mapper.readValue(jsonStr, Weather.class);
List<Property> properties = weather.getProperties();
for (Property property : properties) {
if ("temperature".equals(property.getName())) {
System.out.println(property.getValue());
}
}
}
}
class Weather {
private List<Property> properties;
public List<Property> getProperties() {
return properties;
}
public void setProperties(List<Property> properties) {
this.properties = properties;
}
}
class Property {
private String name;
private String value;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
解释:
- 创建 Weather 和 Property 类: 分别对应 JSON 对象中的
properties属性和 JSON 数组中的每个元素。 - 使用 ObjectMapper 解析 JSON 字符串: 将 JSON 字符串转换为 Weather 对象。
- 遍历属性列表: 通过
getProperties()方法获取 properties 列表,并使用循环遍历每个Property对象。 - 提取
temperature的值: 判断Property对象的name属性是否为temperature,如果是则输出其value属性的值。
输出结果:
47
总结:
使用 Jackson 库可以方便地将 JSON 数组转换为 Java List,并通过循环遍历获取所需属性的值。在实际应用中,可以根据需要修改代码,以提取不同的属性值。
原文地址: https://www.cveoy.top/t/topic/oDI7 著作权归作者所有。请勿转载和采集!