3

What I am trying to achieve is convert a JsonNode to a POJO (i.e. deserialize it) inside a custom deserializer.

Most other answers, like this one here, suggest using ObjectMapper, but the deserialize method specifically does not have the object mapper, so the solutions do not work. This question is therefore not a duplicate.

Here is my custom deserializer:

class AccountDeserializer extends StdDeserializer<Input> {
    public AccountDeserializer() {
        this(null);
    }

    public AccountDeserializer(Class<?> vc) {
        super(vc);
    }

    @Override
    public Account deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        JsonNode root = jp.getCodec().readTree(jp);
        User user = root.get("user").????;

        // other statements

        Account acc = new Account(user);
        return acc;
    }
}

(User is a simple class)

Joe
  • 46,419
  • 33
  • 155
  • 245
mrdaliri
  • 7,148
  • 22
  • 73
  • 107
  • 2
    @MarkRotteveel Hi Mark, you closed this a couple of years ago as a dupe of the linked question, but this one specifically concerns how to do the conversion *without* an ObjectMapper (because it's not available). The other question might be for the more general case, but I'd never use this method if I *did* have the ObjectMapper, so it wouldn't be a very suitable answer for the other question. Similarly, I'd come here, not to the other question, if I was in a Deserializer. – Druckles Nov 28 '22 at 13:51
  • That's why I think they're different questions. And this question also doesn't have an answer over there; just a comment. – Druckles Nov 28 '22 at 13:52
  • I came across this question, and I agree, I don't think it's a duplicate. I've edited and requested it be re-opened. – Joe Aug 17 '23 at 18:12

1 Answers1

3

You can use the ObjectCodec in JsonParser like this:

jp.getCodec().treeToValue(root.get("user"), User.class)

This will give you your User object back according to any other existing serialization rules.

Thanks to @galcyurio for the comment in Convert JsonNode into POJO:

You can also use this method in StdDeserializer: p.codec.treeToValue

Druckles
  • 3,161
  • 2
  • 41
  • 65