Trying to port native gson universal desancializer to jackson

Currently, GSON deserialization and retrofitting using GsonConverterFactory modifications:

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(new TypeToken<Map<Book, Collection<Author>>>(){}.getType(), new BooksDeserializer(context));
Gson gson = gsonBuilder.create();

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(url)
    .addConverterFactory(GsonConverterFactory.create(gson))
    .build();

BookService service = retrofit.create(BookService.class);
Response<Map<Book, Collection<Author>>> response = service.getBooks().execute();    

I would like to use JacksonConverterFactory, which is provided by modification? I would have to provide this to Jackson's cartographer. Is there a way to provide type information to this mapper, as was the case with GSON?

SimpleModule simpleModule = new SimpleModule();
// TODO provide mapper with info needed to deserialize 
// Map<Book, Collection<Author>>
mapper.registerModule(simpleModule);

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(url)
    .addConverterFactory(JacksonConverterFactory.create(mapper))
    .build();

BookService service = retrofit.create(BookService.class);
Response<Map<Book, Collection<Author>>> response = service.getBooks().execute();

Looking specifically at TODO, can I say that the mapper uses this deserializer?

public class BooksDeserializer extends JsonDeserializer<Map<Book, Collection<Author>>> {

    @Override
    public Map<Book, Collection<Author>> deserialize(JsonParser parser, DeserializationContext context) throws IOException, JsonProcessingException {
        // deserialize here
    }
}
+4
source share
2 answers

API SimpleModule.addDeserializer(java.lang.Class, com.fasterxml.jackson.databind.JsonSerializer) of JsonSerializer<T>, T , , , ; TypeReference<Map<Book, Collection<Author>>> Map<Book, Collection<Author>>.

, Java. - ,

@XmlRootElement
public class SerializableBookMapWrapper {

    private Map<Book, Collection<Author>> wrapped;

    public SerializableBookMapWrapper(final Map<Book, Collection<Author>> wrapped) {
        this.wrapped = wrapped;
    }

    public Map<Book, Collection<Author>> getWrapped() {
        return wrapped;
    }

    public void setWrapped(final Map<Book, Collection<Author>> wrapped) {
        this.wrapped = wrapped;
    }
}

- JsonDeserializer<SerializableBookMapWrapper> . , Book Author, .

, ObjectMapper .

+3

, : JsonDeserializer , . , . - ( ), ; Book Author Map, Map deserializer . .

: , , ObjectMapper JSON . , Retrofit, , .

0

Source: https://habr.com/ru/post/1627472/


All Articles