Search code examples
javaandroidjacksonretrofit

How to disable/enable jackson SerializationFeature.WRAP_ROOT_VALUE?


I'm using JSONAPI, so I need to wrap some classes, but not all classes, like:

{"users": {"aKey": "aValue"}} // wrapped.
{"aKey": "aValue"} // not wrapped.

There's a way to disable tis feature dynamically or from the class itself?,

I try this:

To wrap/unwrap I'm doing this:

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
objectMapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

JacksonConverterFactory jacksonConverterFactory = JacksonConverterFactory.create(objectMapper);

OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.interceptors().add(new LoggingInterceptor());

Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(baseUrl)
            .client(okHttpClient)
            .addConverterFactory(jacksonConverterFactory)
            .build();

I need some of the POJOs disable that feature, is that possible?.

Thank you.


Solution

  • Currently, no. This is tracked under FasterXML/jackson-databind#1022 As a workaround, you can create two different retrofit instances one with root enabled converter factory and one without.