Skip to content
Advertisement

How to serialize nested ObjectId to String with Jackson?

There are many questions concerning conversion from ObjectId to String with jackson. All answers suggest either creating own JsonSerializer<ObjectId> or annotating the ObjectId field with @JsonSerialize(using = ToStringSerializer.class).

However, I have a map that sometimes contains ObjectIds, i.e.:

JavaScript

I want jackson to convert it to:

JavaScript

But I get:

JavaScript

I have registered the conversion (in Spring) with

JavaScript

And the first-level ObjectIds are converted correctly. How to make jackson convert also the nested ones? Do I have to write custom converter for this map?

Keep in mind that this Map can be nested multiple times (i.e. contain another maps). I just want to convert ObjectId to String whenever jackson sees it.

Advertisement

Answer

I suppose that you are taking about org.bson.types.ObjectId from org.springframework.boot:spring-boot-starter-data-mongodb. Your code works perfectly fine for me. 1 thing i can see is that you don’t show @Configuration annotation above WebappConfig.

Here is my demo project, can you test it on yours setup?

Application.java

JavaScript

Responce from 127.0.0.1:8080

JavaScript

Gradle:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement