How rename property while serializing/deserializing using Jackson without annotations?

Viewed 20

How to make Jackson rename field id to _id while serializing and vice-versa while deserializing, without adding any annotation on the class?

For example this object:

{
  "id": "abc",
  "value": "foo"
}

should be serialized to:

{
  "_id": "abc",
  "value": "foo"
}

I want it to work for any class, without the need of annotating each id field with @JsonProperty("_id")

1 Answers

I've found a rather nice solution to this problem.

val document = objectMapper.convertValue(data, Document::class.java)
if ("id" in document) {
    document["_id"] = document["id"]
    document.remove("id")
}
objectMapper.writeValueAsString(document)

First convert this object to map/tree-like structure (like Document if you're working with Mongo), which is easy to edit, and after making your changes serialize/deserialize it to your desired format. I'm not sure about a performance of this solution, but it seems to be very straight-forward.

Related