如何在Java中修改YAML并保留注释?是否有适用的解析器?
Absolutely! You can modify an existing YAML file while keeping all its original comments intact—you just need to pick a Java YAML parser that supports comment retention. Let’s walk through this with your sample YAML and practical implementation examples.
First, here’s your sample YAML for reference:
#This is a test YAML name: abcd age: 23 #Test YAML ends here
Recommended Java Parsers for Comment-Retentive YAML Editing
1. SnakeYAML (with CommentedMap)
SnakeYAML is one of the most widely used YAML libraries for Java, and while its default setup doesn’t preserve comments, it provides extended classes like CommentedMap and CommentedList to handle comment-aware data structures.
Here’s a working example to read, modify, and write back your YAML while preserving comments:
import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; import org.yaml.snakeyaml.representer.Representer; import org.yaml.snakeyaml.comments.CommentType; import java.io.FileReader; import java.io.FileWriter; import java.util.List; public class CommentedYamlEditor { public static void main(String[] args) throws Exception { // Initialize YAML parser with CommentedMap as the default map type Yaml yaml = new Yaml(new Constructor(CommentedMap.class), new Representer() { { representers.put(CommentedMap.class, representMap); } }); // Load the YAML file into a CommentedMap (preserves comments) CommentedMap yamlData = yaml.load(new FileReader("test.yaml")); // Modify existing fields yamlData.put("name", "new_test_name"); // Add a new field yamlData.put("email", "user@example.com"); // Optional: Add a comment to the new field yamlData.addComment("email", "Contact email for the user"); // Write the modified data back to file, keeping all original and new comments try (FileWriter writer = new FileWriter("modified_test.yaml")) { yaml.dump(yamlData, writer); } } }
This approach retains all block comments (like the top #This is a test YAML) and inline comments (like #Test YAML ends here next to age). The CommentedMap class tracks comment metadata alongside the YAML key-value pairs.
2. Jackson YAML (with Comment-Enabled Configuration)
If you’re already using the Jackson ecosystem for JSON/YAML processing, you can configure it to preserve comments too. Note that Jackson’s comment support is a bit less granular than SnakeYAML’s, but it works well for basic use cases.
Example code:
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator; import java.io.File; import java.util.Map; public class JacksonYamlEditor { public static void main(String[] args) throws Exception { // Configure YAML factory to read and write comments YAMLFactory yamlFactory = new YAMLFactory() .enable(YAMLGenerator.Feature.WRITE_COMMENTS) .enable(YAMLGenerator.Feature.ALLOW_COMMENTS); ObjectMapper mapper = new ObjectMapper(yamlFactory); // Load YAML into a Map (comments are retained in the background) Map<String, Object> yamlData = mapper.readValue(new File("test.yaml"), Map.class); // Modify data yamlData.put("age", 25); yamlData.put("location", "New York"); // Write back to file with comments preserved mapper.writeValue(new File("modified_test_jackson.yaml"), yamlData); } }
Key Notes
- SnakeYAML gives you more control over comment manipulation (e.g., adding/removing specific comments), making it ideal if you need fine-grained handling.
- Jackson is better integrated if your project already uses Jackson for other serialization tasks.
内容的提问来源于stack exchange,提问作者dexterousashish




