Reputation: 11
I have a json string in the following structure:
{
"1": { ... },
"2": { ... },
"3": { ... }
}
where 1, 2 and 3 are identifiers.
I want to deserialize this string and cast it to the following type - Map<Integer, List<MyCustomPojo>>
The thing is that each value { ... }
has its own structure, but I need to parse them all and cast to a common structure - MyCustomPojo
.
I can do it by implementing a custom deserializer:
public class CustomMapDeserializer extends JsonDeserializer<Map<Integer, List<MyCustomPojo>>> {
@Override
public Map<Integer, List<MyCustomPojo>> deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException {
JsonNode root = jsonParser.getCodec().readTree(jsonParser);
// parse JsonNode and return Map<Integer, List<MyCustomPojo>>
}
Now I need to add this deserializer to a module and then register it with an object mapper.
SimpleModule module = new SimpleModule();
module.addDeserializer(Map.class, new CustomMapDeserializer()); // can’t specify type for map
objectMapper.registerModule(module);
The problem is that now it will be applied to all Map classes in my application. I want it to apply only to parameterized map - Map<Integer, List<MyCustomPojo>>.
Is it possible to do it?
Upvotes: 1
Views: 289
Reputation: 125
Simplest solution should be to create a new class which inherit from Map and use it when you add deserializer
Upvotes: 1
Reputation: 203
The way you're thinking of isn't going to work, and might need to rewrite some of the code to apply ONLY to your parameterized map. I don't want to give any false info, sorry I can't provide a solution, but I hope this comment will help others to provide a solution for other abled coders.
Upvotes: 0