问题
I have a spring boot service using MongoDB as a repository for my beans. I added a feature to download a bean in JSON format and upload it on another system (or simply to have a file backup).
I am using the ObjectMapper
with the writeValueAsString
method. This all works as expected, except that there are additional properties which aren't part of my bean.
All properties that are defined with @DBRef
thus pointing to other beans in the MongoDB have a target
property containing the exact same serialized bean. For ex: I keep track of the user that created the bean through a GUI:
{
createdBy: {
id: "5bb743feacbd6505304c025e",
username: "admin",
target: {
id: "5bb743feacbd6505304c025e",
username: "admin"
}
}
}
Where does this target
come from and is there a way to get rid of it in the JSON?
回答1:
From Java to JSON serialization with Jackson PTH and Spring Data MongoDB DBRef generates extra target property
The Target field is added by Spring Data because it is a lazy collection. So it is like datahandler etc. in Hibernate for JPA.
Option1: To ignore them you just have to add
@JsonIgnoreProperties(value = { "target" })
on class level@Document(collection = "song") @JsonIgnoreProperties(value = { "target" }) public class Song { ... }
Option2: Make the Collection not lazy
Option 3: create your own DBRef serializer as mentioned by Spring Data Mongo + Lazy Load + REST Jackson
来源:https://stackoverflow.com/questions/55047731/where-do-the-target-properties-in-my-json-serialization-come-from