XStream deserialize multimap with enum key

38 views
Skip to first unread message

cyberquarks

unread,
Mar 31, 2021, 1:18:43 AM3/31/21
to XStream User
I recently posted and answer at SO related to this:


It works, however, the issue is the deserialized multimap despite having no errors when deserializing, the conveted multimap seems to included a String key instead of an enum key internally thus the type in compile time would not be able to retrieve the value.

Here's the code:

@Test
public void testSerializeWithEnum() {
XStream xstream = new XStream(new JettisonMappedXmlDriver());
xstream.registerConverter(new MultimapConverter(xstream.getMapper()));
xstream.allowTypeHierarchy(Multimap.class);
xstream.addDefaultImplementation(ArrayListMultimap.class, Multimap.class);
Multimap<TestEnum, String> test = HashMultimap.create();
test.put(TestEnum.E1, "test");
String json = xstream.toXML(test);
System.out.println(json);
final Multimap<TestEnum, String> result = (Multimap<TestEnum, String>)xstream.fromXML(json);
Assert.assertEquals("test", result.get(TestEnum.E1).stream().findFirst());
}

public enum TestEnum {
E1
}

The  result.get(TestEnum.E1) returns an empty array, debugging that point, shows result contains the ArrayList with the value "test" but with a key "E1" 

Jörg Schaible

unread,
Mar 31, 2021, 5:14:25 AM3/31/21
to XStream User, 'cyberquarks' via XStream User
Hi,

On Wednesday, 31. March 2021, 07:18:43 CEST 'cyberquarks' wrote via XStream
User:
Well, look at the unmarshall method of that MultimapConverter. It reads the
key from the "key" attribute and puts is as String into the resulting map.
This is what you get.

Since an attribute cannot keep additionally the type of the key, you should
add an additional parameter to the converter for the key type assuming all
keys are of the same type. The unmarshal method should then use the mapper to
convert the value of the attribute back into the real type of the key.
However, this implies also, that this converter should be registered as local
converter for the member field that holds the Multimap.

Regards,
Jörg




Reply all
Reply to author
Forward
0 new messages