使用Java Streams根据Key2获取对应Key3的值
使用Java Streams匹配JSON对象并获取对应Key3值
没问题,我来帮你一步步实现这个需求:
步骤1:定义对应的Java实体类
首先你需要把API返回的JSON结构映射成Java对象,这样才能用Streams方便处理。假设我们用Jackson(Spring Boot项目默认自带)来做JSON序列化/反序列化,先创建一个实体类:
import com.fasterxml.jackson.annotation.JsonProperty; public class ApiData { @JsonProperty("Key1") private String key1; @JsonProperty("Key2") private String key2; @JsonProperty("Key3") private String key3; @JsonProperty("Key4") private String key4; // 必须要有无参构造函数(Jackson序列化需要) public ApiData() {} // Getter方法,Streams需要通过Getter访问字段 public String getKey2() { return key2; } public String getKey3() { return key3; } // 可选:添加Setter和全参构造函数,方便本地测试 public void setKey2(String key2) { this.key2 = key2; } public void setKey3(String key3) { this.key3 = key3; } }
步骤2:将API返回的JSON转为Java对象列表
接下来把API返回的JSON字符串转换成List<ApiData>对象:
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.List; // 假设apiResponse是你从API获取到的JSON字符串 String apiResponse = "[ {\"Key1\": \"Value1\", \"Key2\": \"Value2A\", \"Key3\": \"Value3A\", \"Key4\": \"Value4A\"}, {\"Key1\": \"Value1\", \"Key2\": \"Value2B\", \"Key3\": \"Value3B\", \"Key4\": \"Value4B\"}, {\"Key1\": \"Value1\", \"Key2\": \"Value2C\", \"Key3\": \"Value3C\", \"Key4\": \"Value4C\"} ]"; ObjectMapper objectMapper = new ObjectMapper(); List<ApiData> dataList = objectMapper.readValue(apiResponse, new TypeReference<List<ApiData>>() {});
步骤3:用Java Streams匹配Key2并提取Key3
现在就可以用Streams过滤出匹配目标Key2的对象,然后提取对应的Key3值。这里推荐用Optional处理可能找不到匹配项的情况,避免空指针异常:
import java.util.Optional; // 假设你已知的目标Key2值是targetKey2 String targetKey2 = "Value2B"; Optional<String> targetKey3 = dataList.stream() // 过滤出Key2等于目标值的对象 .filter(data -> targetKey2.equals(data.getKey2())) // 提取对应的Key3值 .map(ApiData::getKey3) // 获取第一个匹配项(如果有多个匹配取第一个,无匹配则返回空Optional) .findFirst(); // 处理结果:存在则输出,否则做默认值/异常处理 targetKey3.ifPresent(key3 -> System.out.println("匹配到的Key3值:" + key3)); // 或者用orElse设置默认值 String result = targetKey3.orElse("未找到匹配的Key3值");
额外说明
- 如果API返回的JSON中Key2可能有多个匹配项,你可以把
findFirst()换成collect(Collectors.toList()),收集所有匹配的Key3值。 - 如果你用的是Gson而不是Jackson,只需要替换JSON转换部分的代码,Streams的处理逻辑完全一致。
内容的提问来源于stack exchange,提问作者Alex Bloomberg
相关产品推荐
相关产品推荐

