YAML 自定义对象 [英] YAML custom object

查看:51
本文介绍了YAML 自定义对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有简单的 YAML 文档:

I have simple YAML document:

object:
  a: 1
  b: 2
  c: 3

我能否将此属性读取到自定义对象中,该对象仅包含一个带有 1 个参数的构造函数.例如

Could I read this properties to custom object, which contains a constructor only with 1 argument. For example

public class CustomObject {
        private String value;

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

        getValue ...
        setValue ...
    }

其中 value 是属性连接 a,b,c 与掩码的结果(结果为 1:2/3)?

where value is result of properties concatenation a,b,c with mask (as result 1:2/3)?

推荐答案

这可以通过自定义构造函数和表示器实现:

This is possible with custom constructors and representers:

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");

当然,这需要细化处理错误情况,但它显示了大致的想法.要将对象转储为映射,您可以定义一个类似于此处的代码的表示器.有关详细信息,请参阅文档.

Of course, this needs refinement for handling error cases, but it shows the general idea. To dump the object as a mapping, you can define a representer similarly to the code here. See the documentation for more information.

这篇关于YAML 自定义对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆