标签:
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>
1 public class YmalFc<T> { 2 3 private final YAMLFactory yamlFactory; 4 private final ObjectMapper mapper; 5 private final Class<T> klass; 6 7 public YmalFc(Class<T> klass) { 8 this.klass = klass; 9 this.yamlFactory = new YAMLFactory(); 10 this.mapper = new ObjectMapper(); 11 mapper.enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); 12 13 } 14 15 public T build(String path) throws IOException { 16 try { 17 InputStream input =new FileInputStream(path); 18 YAMLParser yamlParser = yamlFactory.createParser(input); 19 final JsonNode node = mapper.readTree(yamlParser); 20 TreeTraversingParser treeTraversingParser = new TreeTraversingParser(node); 21 final T config = mapper.readValue(treeTraversingParser, klass); 22 return config; 23 } catch (Exception e) { 24 throw e; 25 } 26 } 27 28 public static void main(String[] args) { 29 Contact contact = new Contact(); 30 YmalFc<Contact> ymalFc = new YmalFc<Contact>(Contact.class); 31 try { 32 contact = ymalFc.build(new FileConfigurationSourceProvider(), "contact.yml"); 33 } catch (IOException e) { 34 e.printStackTrace(); 35 } 36 } 37 }
1 public class Contact { 2 @JsonProperty 3 public String name; 4 @JsonProperty 5 public int age; 6 7 public String getName() { 8 return name; 9 } 10 public void setName(String name) { 11 this.name = name; 12 } 13 public int getAge() { 14 return age; 15 } 16 public void setAge(int age) { 17 this.age = age; 18 } 19 }
YML文件
contact:
name: Nathan Sweet
age: 28
YML文件像Python 一样是一个需要注意空格缩进的语言。
标签:
原文地址:http://www.cnblogs.com/shouhongxiao/p/5803644.html