Home > Blockchain >  How to add ObjectNodes with same names?
How to add ObjectNodes with same names?

Time:12-02

I am trying to create xml output for web endpoint. Building xml with ObjectNodes - and i fail to add node with the same name, So i need

  <feature_set>
       <feature>
         ...
       </feature>
       <feature>
        ...
       </feature>
....

I am trying to do like this, and it won't work:

ObjectNode featureSetNode = ((ObjectNode) sequenceNode).putObject("feature_set");
        
        for (SimpleFeature feature : simpleFeatures ) {
            JsonNode featureNode = featureSetNode.putObject("feature");
        }

I am getting only one feature node as a result. How can i add nodes with the same name?

CodePudding user response:

You could let jackson automatically convert the object using annotations like this:

@JacksonXmlRootElement(localName = "feature_set")
public static class FeatureRoot {
    @JacksonXmlElementWrapper(useWrapping=false) //this removes wrapper tag
    @JacksonXmlProperty(localName="feature")
    private List<Feature> features;

    public FeatureRoot(List<Feature> features) {
        this.features = features;
    }

    public List<Feature> getFeatures() {
        return features;
    }

}
public static class Feature {
    private String name;

    public Feature(String name) {
        this.name = name;
    }


    public String getName() {
        return name;
    }
}

The following code

    FeatureRoot featureRoot = new FeatureRoot(
        List.of(
            new Feature("test"),
            new Feature("asd")
        )
    );
    XmlMapper mapper = new XmlMapper();
    String xml = mapper.writeValueAsString(featureRoot);

will produce

<feature_set>
    <feature>
        <name>test</name>
    </feature>
    <feature>
        <name>asd</name>
    </feature>
</feature_set>

CodePudding user response:

To create similar-keys entries from scratch is this:

        ObjectNode featureSetNode = sequenceNode.putObject("feature_set");
        ArrayNode featureNode = featureSetNode.putArray("feature");

        for (SimpleFeature feature : simpleFeatures ) {
            ObjectNode featureNodeImpl = featureNode.addObject();
            featureNodeImpl.put("start", feature.getSeqRegionStart());
        }

  • Related