2

我想看看如何在 xtend 项目中使用snakeyaml。

如何转储到 yaml 并从中加载?

package test
...
@Data
final public class D {
  public var Integer a
}

...

val d = new D(2);
val constructor = new Constructor(D)

val y = new Yaml(constructor);
val o = y.dump(new D(2))
val l = new Yaml(constructor).load(o);
println("load: " + l)

错误信息:

Exception in thread "main" Can't construct a java object for tag:yaml.org,2002:test.D; exception=java.lang.NoSuchMethodException: test.D.<init>()
 in 'string', line 1, column 1:
    !!test.D {_a: 2}

我也在尝试:

@Data
final public class D {
    public new(Integer s) {
        _a = s
    }

    public var Integer a

}

没有提供所需的构造函数吗?生成的 Java 类如下所示:

@Data
@SuppressWarnings("all")
public final class D {
  public D(final Integer s) {
    this._a = s;
  }

  public final Integer _a;

  public Integer getA() {
    return this._a;
  }

  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((_a== null) ? 0 : _a.hashCode());
    return result;
  }

  @Override
  public boolean equals(final Object obj) {
    if (this == obj)
      return true;
    if (obj == null)
      return false;
    if (getClass() != obj.getClass())
      return false;
    D other = (D) obj;
    if (_a == null) {
      if (other._a != null)
        return false;
    } else if (!_a.equals(other._a))
      return false;
    return true;
  }

  @Override
  public String toString() {
    String result = new ToStringHelper().toString(this);
    return result;
  }
}

这应该足够构造函数了:

  public D(final Integer s) {
    this._a = s;
  }
4

1 回答 1

1

答案似乎是@Data Annotation 在序列化的上下文中没有意义。使用snakeyaml 进行序列化需要@Property 注解,例如:

public class D {
    @Property String year;
    @Property Map<String, Integer> map;

}

并且在类型铸造方面有很多工作必须手工完成。

val constructor = new Constructor(D); val  yaml = new
Yaml(constructor); val car = yaml.load(...) as D;
于 2014-05-03T07:30:11.737 回答