Replies: 2 comments 3 replies
-
Just to make sure: have you tried adding Alternatively if you wanted to go custom deserializer route, you can similarly annotated one used for Map values (but not Map itself) with
One challenge in both cases, though, is that value deserializer has no access to key of |
Beta Was this translation helpful? Give feedback.
-
Thank you @cowtowncoder
Wow, I thought I'd tried every annotation - everywhere.... but seeingly not this combination. Thank you @Test
public void testJacksonTypeInfo() throws JsonProcessingException {
ThingWithMap twm1 = new ThingWithMap();
twm1.setMyMap1(Map.of("mk1", new MapValue1(), "mk2", new MapValue2(), "i1", 42, "s1", "a string", "b1", true));
twm1.setMyMap2(Map.of("mk1", new MapValue1(), "mk2", new MapValue2(), "i1", 42, "s1", "a string", "b1", true));
String jsonString = objectMapper.writeValueAsString(twm1);
Assertions.assertThat(jsonString).containsOnlyOnce("\"_class\":\"lang.Jackson$MapValue1\"");
Assertions.assertThat(jsonString).containsOnlyOnce("\"_class\":\"lang.Jackson$MapValue2\"");
}
@Data
public static class ThingWithMap
{
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, property = "_class")
private Map<String,Object> myMap1 = new HashMap<>();
private Map<String,Object> myMap2 = new HashMap<>();
}
@Data
public static class MapValue1
{
private String name = "rob";
private int age = -1;
}
@Data
public static class MapValue2
{
private Boolean enabled = true;
private int volume = 11;
} |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Hi,
I have a Map<String,Object> property in a few classes.
I'm trying to workout how to deserialise this effectively, but cannot find a hook to do, pointers appreicated.
My values are not polymorphic, but they could be primitives (double, int, long, boolean, Sring) or a small set of unrelated objects.
In one instance it's OK for me to add type info. I've used
defaultTyping(...)
with aTypeResolverBuilder
and it serialises type info into the values where needed. This deserialises properly too.But this approach has an effect on any generic object, and so other instances of Map<String,Object> fail to deserialise.
It works if I add type info into the JSON as prescribed, but I can't alter some clients who use these interfaces....
(Note: it's mostly things like configurations where most of the time its a primitive, but occasionally some structured data that will evolve slowly)
I could use a different customised ObjectMapper in a few instances if necessary.
Otherwise, is there a (mostly) de-serialisation hook I can use on something like that
I'll also know how to deserialise these values by key name - we have key name conventions for these different types.
Thanks in advance for nay pointers.
R
Beta Was this translation helpful? Give feedback.
All reactions