2016-12-12 92 views
0

我有简单的YAML文件:YAML自定义对象

object: 
    a: 1 
    b: 2 
    c: 3 

我能读这个属性自定义对象,其中包含一个构造函数只有1个说法。例如

public class CustomObject { 
     private String value; 

     public CustomObject(String value) { 
      .... 
     } 

     getValue ... 
     setValue ... 
    } 

其中值是属性的结果级联的a,b,c相掩模(如结果1:2/3)?

回答

1

这是可能的自定义构造函数和申述:

class CustomObjectConstructor extends Constructor { 
    public CustomObjectConstructor() { 
     this.yamlConstructors.put(new Tag("!customObject"), new ConstructCustomObject()); 
    } 

    private class ConstructCustomObject extends AbstractConstruct { 
     public Object construct(Node node) { 
      final Map<Object, Object> values = constructMapping(node); 
      final String a = (String) values.get("a"); 
      final String b = (String) values.get("b"); 
      final String c = (String) values.get("c"); 
      return new CustomObject(a + ":" + b + "/" + c); 
     } 
    } 
} 

您可以使用它像这样:

Yaml yaml = new Yaml(new CustomObjectConstructor()); 
CustomObject myObject = 
    (CustomObject) yaml.load("!customObject\na: 1\nb: 2\nc: 3"); 

当然,这需要细化处理错误的情况下,但它显示了一般理念。要将对象转储为映射,您可以在此定义代表类似于代码的表示器。有关更多信息,请参阅documentation