YAML文件解析

      YAML是一種記語的外語縮寫,YAML 是一種比JSON(json多層次{ 與 [ 會被搞暈的)更直觀的表現形式,展現上更易查錯和關係描述。由於不須要一個專業工具就能夠排查正確性。YAML目前有多種語言提供了支持。node

  JAVA最終是要被序列化或反序列化,Jackson 提供了YAMLFactory.,能夠方便解析YAML,而且能夠無縫結合ObjectMapper.對原有系統改動最小。json

Maven 引用如下包app

 <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文件ide

contact:
  name: Nathan Sweet
  age: 28

YML文件像Python 同樣是一個須要注意空格縮進的語言。工具

相關文章
相關標籤/搜索