【问题标题】:Force YAML Tag on JavaBean properties在 JavaBean 属性上强制使用 YAML 标记
【发布时间】:2016-06-13 16:22:50
【问题描述】:

我一直在使用 SnakeYAML 进行某些序列化/反序列化。我的应用程序结合了 Python 和 Java,因此我需要对标签和类型进行一些“合理的行为”。

我在 YAML 文档上的问题/实际状态:

!!mypackage.MyClassA
someFirstField: normal string
someSecondField:
  a: !!mypackage.ThisIsIt
    subField: 1
    subOtherField: 2
  b: !!mypackage.ThisIsIt
    subField: 3
    subOtherField: 4
someThirdField:
  subField: 5
  subOtherField: 6

我通过重新实现checkGlobalTag 并简单地执行return 实现了对集合内标签的使用(参见示例someSecondField)。如果我理解正确的话,这可以确保 snakeyaml 没有智能清洁并维护标签。到目前为止一切顺利:我到处都需要这种类型。

但是,这还不够,因为someThirdField 也是!!mypackage.ThisIsIt,但它有隐式标签,这是一个问题(Python 不理解)。还有一些其他的极端情况并不重要(试图在 Python 端走一些捷径,结果变成了一个坏主意)。

确保标记出现在所有用户定义的类中的正确方法是什么?我假设我应该重写Representer 上的一些方法,但我一直无法找到哪个方法。

【问题讨论】:

    标签: java snakeyaml


    【解决方案1】:

    负责“智能标签自动清理”的行如下:

    if (property.getType() == propertyValue.getClass())
    

    可以在 representJavaBeanProperty 中找到 Representer 类。

    我发现的(丑陋的)解决方案是将Representer@Override 扩展为representJavaBeanProperty,如下所示:

    protected NodeTuple representJavaBeanProperty(Object javaBean, 
            Property property,
            Object propertyValue, 
            Tag customTag) {
        // Copy paste starts here...
    
        ScalarNode nodeKey = (ScalarNode) representData(property.getName());
        // the first occurrence of the node must keep the tag
        boolean hasAlias = this.representedObjects.containsKey(propertyValue);
    
        Node nodeValue = representData(propertyValue);
    
        if (propertyValue != null && !hasAlias) {
            NodeId nodeId = nodeValue.getNodeId();
            if (customTag == null) {
                if (nodeId == NodeId.scalar) {
                    if (propertyValue instanceof Enum<?>) {
                        nodeValue.setTag(Tag.STR);
                    }
                }
                // Copy-paste ends here !!!
                // Ignore the else block --always maintain the tag.
            }
        }
    
        return new NodeTuple(nodeKey, nodeValue);
    

    这也会强制执行显式标记列表行为(之前通过覆盖 checkGlobalTag 方法强制执行,现在已在 representJavaBeanProperty 代码中实现)。

    【讨论】:

      猜你喜欢
      • 2014-06-24
      • 1970-01-01
      • 1970-01-01
      • 2019-06-21
      • 2012-12-17
      • 1970-01-01
      • 1970-01-01
      • 2016-07-04
      • 1970-01-01
      相关资源
      最近更新 更多