Java 中使用 Yaml

JYaml :读取配置文件等一些操作相对比较方便
Object o = Yaml.load( new File(“…”)) 就可以把Yaml的配置读进变量了,
而 String s = Yaml.dump(object) 也可以很方便地前变量导出成 yaml String
 
可惜比较麻烦的是,没有无参的构造方法的对象将会被导出失败。包括 java.sql.Timestamp ,没有扩展的支持。
另外是 官方已经没有再更新版本了。
相比之下, Snake YAML 就值得推荐了。它更像一个传输数据能力介于XMLRPC 和 对象序列化中间的,轻量级的数据传输方式。
对象序列化可以将对象所有的属性全部序列化成字符串来传输,但是会和.class 文件的时间戳等比较 ,跨平台的可用性较低。
XMLRPC的数据传输必须靠XML来进行。具体传输的内容还是其于Vector,HashTable的
 
而Snake YAML 可以很好的将对象导出成YAML,再在另一个平台中转换成相应的对象。
好处就是,
1、遇到通用对象的时候能够不破坏封装性地传输数据 (OBJ 2 YAML string in Server 和 YAML string 2 OBJ in Client 能够黑盒化 YAML string)。
2、同时也支持HashTable的传递,也就是说兼容XMLRPC等的应用环境。
3、YAML的轻量级与可读性。
 
附简单例子
Object o = new Object();
Yaml y = new Yaml();
String s = y.dump(obj);
Object antherObj = y.load(s);
附稍复杂的没有无参构造方法的,交互传递的例子(根据官网的修改)
 

Class Test{
  public static class Dice{
    private int i;
    private int j;
    public Dice(int i,int j)
    {
      this.i = i;
      this.j = j;
    }
    public int getI() {
      return i;
    }
    public int getJ() {
      return j;
    }
    public void setJ(int j) {
      this.j = j;
    }
    public void setI(int i) {
      this.i = i;
    }
  }
  public static class DiceRepresenter extends Representer {
    public DiceRepresenter() {
      this.representers.put(Dice.class, new RepresentDice());
  }
  private class RepresentDice implements Represent {
    public Node representData(Object data) {
      Dice dice = (Dice) data;
      String value = dice.getI() + "d" + dice.getJ();
      return representScalar(new Tag("!dice"), value); //这个Tag 就是相对应的默认是带包的全路径类名,如果是跨平台,可以指定统一的格式
    }
  }
  }
  public static class DiceConstructor  extends Constructor{
    public DiceConstructor() {
      this.yamlConstructors.put(new Tag("!dice"), new ConstructDice()) //与上面的Tag 相对应
  }
  private class ConstructDice extends AbstractConstruct {
    public Object construct(Node node) {
      ScalarNode sn = (ScalarNode) node;
      String val = (String) constructScalar(sn);
      int position = val.indexOf('d');
      Integer a = Integer.parseInt(val.substring(0, position));
      Integer b = Integer.parseInt(val.substring(position + 1));
      return new Dice(a, b);
    }
  }
  }
  public static void main(String[] args) throws Exception
  {
  Dice x = new Dice(1,2);
  Yaml y = new Yaml(new DiceConstructor (),new DiceRepresenter());
  String s = y.dump(x);
  System.out.println(y.dump(x));
  Dice xdup = (Dice) y.load(s);
  System.out.println(xdup.getI() + "," + xdup.getJ());
  }
}


官网地址

reeoo.com - web design inspiration

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注