I have HashMap<String, Object> that is serialized into xml. When Object is null
HashMap<String, Object> h1 = new HashMap<>();
h1.put("test", null);
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(h1));
Jackson generates something like these
<HashMap>
<test/>
</HashMap>
So I need somehow add attributes to this empty tag
<HashMap>
<test attribute = "something"/>
</HashMap>
Is it possible?
CodePudding user response:
You can do it like this ...
Instead of a null
you need to use something like a thin wrapper around it, which will instruct XmlMapper
to print this attribute information.
Here's a working test which solves the problem.
public class TestXml {
class NullWrapper {
@JacksonXmlProperty(isAttribute = true)
private String attribute = "something";
}
@Test
void test() throws JsonProcessingException {
var mapper = new XmlMapper();
var h1 = new HashMap<>();
h1.put("test", new NullWrapper());
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(h1));
}
}
Output is ...
<HashMap>
<test attribute="something"/>
</HashMap>
Does this solve your problem ? Tell me in the comments.