YAML是“另一种标记语言”的外语缩写,YAML 是一种比JSON(json多层次{ 与 [ 会被搞晕的)更直观的表现形式,展示上更易查错和关系描述。因为不需要一个专业工具就可以排查正确性。YAML目前有多种语言提供了支持。
JAVA最终是要被序列化或反序列化,Jackson 提供了YAMLFactory.,可以方便解析YAML,并且可以无缝结合ObjectMapper.对原有系统改动最小。
Maven 引用以下包
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
<version>2.3.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.3.3</version>
</dependency>
public class YmalFc<T> { private final YAMLFactory yamlFactory;
private final ObjectMapper mapper;
private final Class<T> klass; public YmalFc(Class<T> klass) {
this.klass = klass;
this.yamlFactory = new YAMLFactory();
this.mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); } public T build(String path) throws IOException {
try {
InputStream input =new FileInputStream(path);
YAMLParser yamlParser = yamlFactory.createParser(input);
final JsonNode node = mapper.readTree(yamlParser);
TreeTraversingParser treeTraversingParser = new TreeTraversingParser(node);
final T config = mapper.readValue(treeTraversingParser, klass);
return config;
} catch (Exception e) {
throw e;
}
} public static void main(String[] args) {
Contact contact = new Contact();
YmalFc<Contact> ymalFc = new YmalFc<Contact>(Contact.class);
try {
contact = ymalFc.build(new FileConfigurationSourceProvider(), "contact.yml");
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class Contact {
@JsonProperty
public String name;
@JsonProperty
public int age; public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
YML文件
contact:
name: Nathan Sweet
age: 28
YML文件像Python 一样是一个需要注意空格缩进的语言。