Tomáš Mika
Tomáš Mika

Reputation: 330

Jackson deserialise JsonPatch with object value

I'mu using JsonPatch (JSR-374) with implementation from Apache org.apache.johnzon:johnzon-core:1.2.4 in my Spring project PATCH endpoint:

@Bean
@Primary
public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
    ObjectMapper objectMapper = builder.createXmlMapper(false).build();
    objectMapper.registerModule(new Jdk8Module());
    objectMapper.registerModule(new JSR353Module());
    return objectMapper;
}

Controller

@PatchMapping("/settings")
public ResponseEntity<SettingsResponse> patchSettings(@RequestBody JsonPatch patchDocument, Locale locale) {...}

With json request of a simple atomic values

[
  { "op": "replace", "path": "/currency", "value": "EUR" },
  { "op": "test", "path": "/version", "value": 10 }
]

JsonPatch instance is deserialised correctly by Jackson

But with complex value type (object):

[
  { "op": "replace", "path": "/currency", "value": {"code": "USD", "label": "US Dollar"} },
  { "op": "test", "path": "/version", "value": 10 }
]

Exception is thrown

Caused by: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of javax.json.JsonPatch (no Creators, like default construct, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information at [Source: (PushbackInputStream); line: 1, column: 1]

I recon JsonPatch (and its Apache JsonPatchImpl) is capable of working with complex types as JsonValue mentions JsonObject and ValueType.OBJECT, but I don't know how to instruct Jackson to deserialise correctly

Thanks in advance for any suggestions or help!

Upvotes: 3

Views: 3289

Answers (2)

Taraskin
Taraskin

Reputation: 792

In addition to the mentioned above by Tomáš Mika I would add my comment / use-case.

Pre-conditions

  • Spring-Boot + Lombok + Jackson + JsonPatch usage
  • JsonPatchHttpMessageConverter - as defined above

At some point after colleagues cleanup commit all PATCH APIs have stopped working, by throwing the InvalidDefinitionException with error message:

Cannot construct instance of `javax.json.JsonValue` (no Creators, like default constructor, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information\n at [Source: UNKNOWN; byte offset: #UNKNOWN]

After some time & investigation it was found that:

  • Exception has thrown by ObjectMapper deserializer, specifically in method:

    protected Object _convert(Object fromValue, JavaType toValueType)

line #4388:

result = deser.deserialize(p, ctxt);

The reason was missing ObjectMapper bean, previously created to enable JsonPatch and lately removed by mistake in scope of some cleanup:

@Bean
public ObjectMapper objectMapper() {
    return new ObjectMapper()
            .setDefaultPropertyInclusion(JsonInclude.Include.NON_NULL)
            .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
            .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
            .findAndRegisterModules();
}

This ObjectMapper bean has been explicitly defined, in addition to the extensive configuration:

@Configuration
public class WebConfiguration implements WebMvcConfigurer {

@Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}")
private String dateFormatPattern;

@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
    converters.forEach(converter -> {
        if (converter instanceof MappingJackson2HttpMessageConverter) {
            MappingJackson2HttpMessageConverter jacksonConverter = (MappingJackson2HttpMessageConverter) converter;
            ObjectMapper objectMapper = jacksonConverter.getObjectMapper();
            jacksonConverter.setPrettyPrint(true);
            configureObjectMapper(objectMapper);
        }
    });
}

private void configureObjectMapper(ObjectMapper mapper) {
    mapper.setTimeZone(TimeZone.getTimeZone("UTC"));
    mapper.setDateFormat(new SimpleDateFormat(dateFormatPattern));

    // https://programming.vip/docs/61b9674a30f8c.html
    mapper.setVisibility(
            mapper.getSerializationConfig().getDefaultVisibilityChecker()
                    .withFieldVisibility(JsonAutoDetect.Visibility.ANY)
                    .withGetterVisibility(JsonAutoDetect.Visibility.NONE)
                    .withSetterVisibility(JsonAutoDetect.Visibility.NONE)
                    .withCreatorVisibility(JsonAutoDetect.Visibility.NONE)
    );

    // Serializers
    mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
    mapper.setDefaultPropertyInclusion(JsonInclude.Include.NON_EMPTY);
    mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    mapper.disable(SerializationFeature.FAIL_ON_SELF_REFERENCES);
    mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    mapper.disable(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS);
    mapper.disable(SerializationFeature.FAIL_ON_UNWRAPPED_TYPE_IDENTIFIERS);

    // Deserializers
    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    mapper.disable(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE);
    mapper.disable(DeserializationFeature.FAIL_ON_UNRESOLVED_OBJECT_IDS);
    mapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
    mapper.disable(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS);

    mapper.registerModule(hibernate5Module());
    mapper.registerModule(new JavaTimeModule());
}

    @Bean
public Module hibernate5Module() {
    Hibernate5Module hibernate5Module = new Hibernate5Module();
    hibernate5Module.enable(Hibernate5Module.Feature.REPLACE_PERSISTENT_COLLECTIONS);
    return hibernate5Module;
  }
}

Upvotes: 1

Tom&#225;š Mika
Tom&#225;š Mika

Reputation: 330

I went through this by using the JSR-364 Implementation Json.createPatch:

@PatchMapping("/settings")
public ResponseEntity<SettingsResponse> patchDefaultSettingsJsonP3(@RequestBody String patchString, Locale locale) {
    try (JsonReader jsonReader = Json.createReader(new StringReader(patchString))) {
        JsonPatch patch = Json.createPatch(jsonReader.readArray());
        ...
    }
}

EDIT: I found wiser solution by registering the converter as a bean. Spring then takes care of the deserialisation internally

@Component
public class JsonPatchHttpMessageConverter extends AbstractHttpMessageConverter<JsonPatch> {

public JsonPatchHttpMessageConverter() {
    super(MediaType.valueOf("application/json-patch+json"), MediaType.APPLICATION_JSON);
}

@Override
protected boolean supports(Class<?> clazz) {
    return JsonPatch.class.isAssignableFrom(clazz);
}

@Override
protected JsonPatch readInternal(Class<? extends JsonPatch> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    try (JsonReader reader = Json.createReader(inputMessage.getBody())) {
        return Json.createPatch(reader.readArray());
    } catch (Exception e) {
        throw new HttpMessageNotReadableException(e.getMessage(), inputMessage);
    }
}

@Override
protected void writeInternal(JsonPatch jsonPatch, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
    throw new NotImplementedException("The write Json patch is not implemented");
}
}

Upvotes: 3

Related Questions