user4122863
user4122863

Reputation:

Snakeyaml removed quotes

How do I configure snakeyaml to remove the following single quotes?

#%RAML 1.0 DataType
type: object
properties:
  apiName:
    type: string
  label:
    type: string
  sortable:
    type: '!include boolean-types.raml'

I am using snakeyaml to output RAML, I need to remove the single quotes on the include.

I have configured the options as follows:

DumperOptions options = new DumperOptions();
options.setIndent(2);
options.setPrettyFlow(true);
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
Yaml yaml = new Yaml(options);
yaml.dump(map, writer);

Upvotes: 0

Views: 751

Answers (2)

user4122863
user4122863

Reputation:

To parse the file with the !include you can do the following.

import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.constructor.AbstractConstruct;
import org.yaml.snakeyaml.constructor.Constructor;
import org.yaml.snakeyaml.nodes.Node;
import org.yaml.snakeyaml.nodes.ScalarNode;
import org.yaml.snakeyaml.nodes.Tag;

public class IncludeConstructor extends Constructor {
    public IncludeConstructor(LoaderOptions options) {
        super(options);
        this.yamlConstructors.put(new Tag("!include"), new ConstructIncludeTag());
    }

    private class ConstructIncludeTag extends AbstractConstruct {
        public Object construct(Node node) {
            ScalarNode scalarNode = (ScalarNode) node;
            return "!include " + scalarNode.getValue();
        }
    }
}


Yaml yaml = new Yaml(new IncludeConstructor(new LoaderOptions()));

Upvotes: 0

flyx
flyx

Reputation: 39708

This line:

  type: '!include boolean-types.raml'

is a key type with the scalar value !include boolean-types.raml.

This proposed line:

type: !include boolean-types.raml

is a key type with a scalar value boolean-types.raml, where the scalar node has the explicit tag !include.

They are different in semantics. You are apparently giving SnakeYAML data that contains the former and then expect it to output the latter. That can't work, YAML serialization keeps the semantics of the given data. You need to give data that represents the semantics you want to have in the YAML file.

For example, you could define an Include class with a custom representer:

class Include {
    public String path;
}

class IncludeRepresenter extends Representer {
    public IncludeRepresenter(DumperOptions options) {
        super(options);
        this.representers.put(Include.class, new RepresentInclude());
    }

    private class RepresentInclude implements Represent {
        public Node representData(Object data) {
            Include incl = (Include) data;
            return representScalar(new Tag("!include"), incl.path);
        }
    }
}

Then you can do

Yaml yaml = new Yaml(new IncludeRepresenter(), options);

and use an Include object where you want to produce the value shown above.

Upvotes: 1

Related Questions