Where do the “target” properties in my JSON serialization come from?

别来无恙 提交于 2019-12-13 03:35:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!