简体   繁体   English

对象树结构的JSON序列化

[英]JSON serialization of an object tree structure

When serializing my POJOs with relationships, I used to create different views for each of my classes. 当使用关系序列化POJO时,我曾经为每个类创建不同的视图。 For every class, I created a view Basic , displaying only scalar properties, and Detail including in top of that all my relationships. 对于每个类,我创建了一个Basic视图,仅显示标量属性,并且在所有关系的最上方显示了Detail It looks like this : 看起来像这样:

public class Stage extends BasicDomainObject {

    @JsonView(Views.Stage.Basics.class)
    protected String stageType = "";

    @JsonView(Views.Stage.Basics.class)
    protected String scheduledReleaseGraph = "";

    @JsonView(Views.Stage.Details.class)
    private Pipeline pipeline;

    // ...
}

Then, in my REST api layer, I could serialize the correct view by specifying the right one: 然后,在我的REST api层中,我可以通过指定正确的视图来序列化正确的视图:

mapper.writerWithView(Views.Stage.Details.class).writeValueAsString(bean);

Now, I had to add a field private Stage parentStage in my Stage class. 现在,我必须在我的Stage类中添加一个字段private Stage parentStage I'm trying to have an output looking like this with my Details view : 我正在尝试使用我的Details视图使输出看起来像这样:

{
    "id": 2,
    "type": "dev",
    "scheduledReleaseGraph" "xxx",
    "pipeline" : {
         ...
    },
    "parent" : {
        "id": 1,
        "type": "dev",
        "scheduledReleaseGraph" "yyy"
    }
}

The goal here is to display the parent association with only one level of depth. 这里的目标是仅显示一个深度级别的parent关联。 What is the common pattern to achieve this ? 实现此目的的通用模式是什么?

If you use Jackson 2.0, I would look into the JsonIdentityInfo attribute: https://fasterxml.github.io/jackson-annotations/javadoc/2.0.0/com/fasterxml/jackson/annotation/JsonIdentityInfo.html 如果您使用Jackson 2.0,我将研究JsonIdentityInfo属性: https ://fasterxml.github.io/jackson-annotations/javadoc/2.0.0/com/fasterxml/jackson/annotation/JsonIdentityInfo.html

This annotation helps you to handle cyclic references when serializing/deserializing. 此批注可帮助您在序列化/反序列化时处理循环引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM