Bartek
Bartek

Reputation: 41

How to deserialise object with dynamic values into XML attribute

I have a class as follow:

    public class MyObject {
        @JacksonXmlElementWrapper(localName = "Modules")
        @JacksonXmlProperty(localName = "Module", isAttribute = true)
        List<Map<String, String>> modules;

        public List<Map<String, String>> getModules() {
            return modules;
        }

        public void setModules(List<Map<String, String>> modules) {
            this.modules = modules;
        }
    }

which I serialize with

    @Test
    void testMapToAttribute() throws JsonProcessingException {

        MyObject myObject = new MyObject();
        myObject.setModules(List.of(Map.of("k1", "v1", "k3", "v3"), Map.of("k2", "v2")));

        System.out.println(xmlMapper.writeValueAsString(myObject));

    }

and this is the result that I would like to get

<MyObject>
  <Modules>
    <Module k2="v2" />
    <Module k1="k1" k3="k3" />
  </Modules>
</MyObject>

but with the code above, I get

<MyObject>
  <Modules>
    <Module k2="v2"/>
    <Module>
      <k1>v1</k1>
      <k3>v3</k3>
    </Module>
  </Modules>
</MyObject>

Second element's values are not serialized into attributes. Any ideas how to fix it?

Upvotes: 0

Views: 35

Answers (0)

Related Questions