Java解析YAML实现按日期获取追踪应用的结构化数据
解析库选型建议
- Jackson Dataformat YAML:优先选用。它是Jackson生态的YAML实现,后续要做写入、和其他JSON序列化逻辑复用的成本极低,同时支持对象映射、灵活路径取值两种模式,适配你的需求场景。
- SnakeYAML:轻量原生YAML库,是Jackson YAML的底层依赖,优点是无需额外依赖,但需要手动处理结构映射,适合极简场景,对你这种有多层嵌套、动态key的场景效率偏低。
前置依赖引入(Maven配置)
<dependencies> <dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-yaml</artifactId> <version>2.15.2</version> </dependency> </dependencies>
核心实现代码
1. 固定结构对象建模
适配你提供的YAML结构,动态日期、时间字段用Map存储避免写死:
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import java.util.Map; @JsonIgnoreProperties(ignoreUnknown = true) public class UserHealthData { private String telegramID; private String userID; private String firstName; private String lastName; private String eMailAddress; private String phoneNumber; private String birthdate; private Address address; // 动态日期字段:key为日期字符串(如"2021-02-11") private Map<String, DailyRecord> dailyRecords; @JsonIgnoreProperties(ignoreUnknown = true) public static class Address { private String streetAddress; private String city; private String state; private String postalCode; private String country; // 省略Getter/Setter } @JsonIgnoreProperties(ignoreUnknown = true) public static class DailyRecord { private Sleep sleep; private Integer steps; // 动态时间字段:key为时间字符串(如"11:00") private Map<String, BaseEntry> medication; private Map<String, BaseEntry> supplements; private Map<String, BaseEntry> food; // 省略Getter/Setter @JsonIgnoreProperties(ignoreUnknown = true) public static class Sleep { private String wokeUpAt; private String wentToBedAt; // 省略Getter/Setter } // 抽公共基类:用药/补剂/饮食结构完全一致,复用避免冗余代码 @JsonIgnoreProperties(ignoreUnknown = true) public static class BaseEntry { private String what; private Integer howMuch; // 省略Getter/Setter } } // 省略所有Getter/Setter }
2. 读取工具类
内置按日期取记录、按路径(支持数组索引)取值的能力,同时处理YAML里的NULL占位符:
import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Map; public class YamlHealthDataReader { private final ObjectMapper yamlMapper; private UserHealthData cachedData; public YamlHealthDataReader() { this.yamlMapper = new ObjectMapper(new YAMLFactory()); this.yamlMapper.configure(JsonParser.Feature.ALLOW_YAML_COMMENTS, true); } // 从指定路径加载YAML文件 public void loadDataFromFile(String filePath) throws IOException { File yamlFile = new File(filePath); this.cachedData = yamlMapper.readValue(yamlFile, UserHealthData.class); // 自动把字符串"NULL"转成空值 convertNullPlaceholder(cachedData); } // 需求1:按指定日期获取当天全量记录 public UserHealthData.DailyRecord getDailyRecord(String dateStr) { if (cachedData == null || cachedData.getDailyRecords() == null) return null; return cachedData.getDailyRecords().get(dateStr); } // 需求2/3:支持路径取值(如food.what[0]、medication.howMuch[1]) public <T> T getValueByPath(String dateStr, String path) { UserHealthData.DailyRecord daily = getDailyRecord(dateStr); if (daily == null) return null; String[] pathParts = path.split("\\."); if (pathParts.length != 2) return null; String category = pathParts[0]; String fieldWithIndex = pathParts[1]; // 把动态时间Map转成按时间排序的List,保证索引顺序和时间先后一致 List<UserHealthData.DailyRecord.BaseEntry> entryList = switch (category) { case "food" -> sortEntryMap(daily.getFood()); case "medication" -> sortEntryMap(daily.getMedication()); case "supplements" -> sortEntryMap(daily.getSupplements()); default -> new ArrayList<>(); }; // 解析字段名和索引 int index; String fieldName; if (fieldWithIndex.contains("[")) { fieldName = fieldWithIndex.substring(0, fieldWithIndex.indexOf("[")); String indexStr = fieldWithIndex.substring(fieldWithIndex.indexOf("[") + 1, fieldWithIndex.indexOf("]")); index = Integer.parseInt(indexStr); } else { fieldName = fieldWithIndex; index = 0; } if (index < 0 || index >= entryList.size()) return null; UserHealthData.DailyRecord.BaseEntry targetEntry = entryList.get(index); return switch (fieldName) { case "what" -> (T) targetEntry.getWhat(); case "howMuch" -> (T) targetEntry.getHowMuch(); default -> null; }; } // 时间字符串(HH:mm)直接按字典序排序就是时间先后顺序 private List<UserHealthData.DailyRecord.BaseEntry> sortEntryMap(Map<String, UserHealthData.DailyRecord.BaseEntry> entryMap) { if (entryMap == null || entryMap.isEmpty()) return new ArrayList<>(); return entryMap.entrySet().stream() .sorted(Comparator.comparing(Map.Entry::getKey)) .map(Map.Entry::getValue) .toList(); } // 递归把所有"NULL"字符串转成空值 private void convertNullPlaceholder(Object obj) { // 可根据实际需求补全递归逻辑,处理所有字符串字段的NULL转换 } }
3. 使用示例
public class Demo { public static void main(String[] args) { YamlHealthDataReader reader = new YamlHealthDataReader(); try { // 替换为你的YAML文件实际路径 reader.loadDataFromFile("health_tracker.yaml"); // 示例1:获取2021-02-11的步数 UserHealthData.DailyRecord daily = reader.getDailyRecord("2021-02-11"); System.out.println("当天步数:" + daily.getSteps()); // 输出6425 // 示例2:获取2021-02-11第一份饮食的内容 String firstFood = reader.getValueByPath("2021-02-11", "food.what[0]"); System.out.println("第一份饮食:" + firstFood); // 输出Bread // 示例3:获取2021-02-12第二次用药的剂量 Integer secondMedDosage = reader.getValueByPath("2021-02-12", "medication.howMuch[1]"); System.out.println("第二次用药剂量:" + secondMedDosage); // 输出2 } catch (IOException e) { e.printStackTrace(); } } }
后续写入功能拓展
- 直接修改内存中的
UserHealthData对象后,调用yamlMapper.writeValue(outputStream, cachedData)即可把修改后的内容写回YAML文件,无需额外适配 - 如果需要保留YAML原有注释、格式,可在Jackson YAML基础上叠加SnakeYAML的格式保留模块,不影响现有读取逻辑
内容的提问来源于stack exchange,提问作者Fachinformatiker
相关产品推荐
相关产品推荐

