Home > Software design >  Java XML Jackson parsing xml to object and ignore some elements
Java XML Jackson parsing xml to object and ignore some elements

Time:06-10

I want to get the fields of model_tree into an object.

<form>
  <model_trees>
    <entry>
        <tree_kind>kind</tree_kind>
        <age>10</age>
    </entry>
  </model_trees>
</form>

@JsonIgnoreProperties(ignoreUnknown=true)
@JacksonXmlRootElement(localName = "model_trees")
public class ModelTrees extends BaseEntity {
  @JacksonXmlProperty(localName = "tree_kind")
  private String treeKind;
  @JacksonXmlProperty
  private int age;
}

Is there a way to not create additional classes for "form"/"entry" elements?

CodePudding user response:

try a custom deserializer, e.g.

class DeSerializer extends StdDeserializer<ModelTrees> {

    protected DeSerializer() {
        super(ModelTrees.class);
    }

    @Override
    public ModelTrees deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        JsonNode node = jp.getCodec().readTree(jp);

        JsonNode treesNode = node.get("model_trees");

        JsonNode entryNode = treesNode.get("entry");

        return new ModelTrees(entryNode.get("tree_kind").textValue(), entryNode.get("age").asInt());
    }
}

Model class:

public class ModelTrees {
    private String treeKind;
    private int age;

    public ModelTrees(String treeKind, int age) {
        this.treeKind = treeKind;
        this.age = age;
    }
}

Register custom mapper:

XmlMapper mapper = new XmlMapper();
SimpleModule module = new SimpleModule("configModule",   com.fasterxml.jackson.core.Version.unknownVersion());
module.addDeserializer(ModelTrees.class, new DeSerializer());
mapper.registerModule(module);
  • Related