Jackson deserialize object or array

前端 未结 4 1986
梦如初夏
梦如初夏 2020-12-09 04:14

I have a Jackson Question.

Is there a way to deserialize a property that may have two types, for some objects it appears like this

\"someObj\" : { \"         


        
4条回答
  •  攒了一身酷
    2020-12-09 04:40

    None of the other answers worked for me:

    • We can't use a modifier since the ObjectMapper cannot be modified and we use a @JsonDeserialize annotation to install the deserializer.
    • We don't have access to the ObjectMapper either.
    • We need the resulting Map to be properly typed, which didn't seem to work with ObjectCodec.treeToValue.

    This is the solution that finally worked:

    public class EmptyArrayToEmptyMapDeserializer extends JsonDeserializer> {
        @Override
        public Map deserialize(JsonParser parser,
                DeserializationContext context) throws IOException {
            if (parser.getCurrentToken() == JsonToken.START_ARRAY) {
                // Not sure what the parser does with the following END_ARRAY token, probably ignores it somehow.
                return Map.of();
            }
            return context.readValue(parser, TypeFactory.defaultInstance().constructMapType(Map.class, String.class, SomeComplexType.class));
        }
    }
    

提交回复
热议问题