Jackson批注创建本地JSON引用

时间:2019-03-13 14:05:20

标签: java json jackson jersey-2.0

我具有以下课程结构

public class A {
    @Id
    public String id;


    public List<B> bs;
}

public class B{
    public String name;

    public List<B> preconditions;

}

如果我返回此类的实例,则会得到嵌套的JSON结构

{
    "id": "3",
    "bs": [
        {
            "name": "abc"
        },
        {
            "name": "drilling",
            "preconditions": [
                {
                    "name": "abc"
                }
            ]
        }
    ]
}

我希望先决条件成为引用列表,例如

{
    "id": "3",
    "bs": [
        {
            "name": "abc"
        },
        {
            "name": "drilling",
            "preconditions": 
                    ["abc"]
        }
    ]
}

我该怎么做?前提条件应引用bs列表中的对象,我将Jersey Web SerevicesJackson用于JSON生成。

编辑:基于MichałZiober答案: 它工作正常,但是如果我更改bs的顺序,结果将如下所示:

{
    "id": "3",
    "bs": [
        {
            "name": "drilling",
            "preconditions": 
                    [
                       {
                            "name": "abc"
                       }
                    ]
        },"abc"
    ]
}

我希望对象总是在bs列表中定义,而不是在前提条件列表中

{
    "id": "3",
    "bs": [
        {
            "name": "drilling",
            "preconditions": 
                    ["abc"]
        }, 
        {
            "name": "abc"
        }
    ]
}

1 个答案:

答案 0 :(得分:0)

您需要使用JsonIdentityInfo批注。您的POJO类可能如下所示:

class A {

    private String id;

    @JsonIdentityInfo(property = "name", generator = ObjectIdGenerators.PropertyGenerator.class)
    private List<B> bs;

    // getters, setters
}

class B {

    private String name;

    @JsonIdentityInfo(property = "name", generator = ObjectIdGenerators.PropertyGenerator.class)
    private List<B> preconditions;

    // getters, setters
}

简单的例子:

import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import java.util.Arrays;
import java.util.List;

public class JsonApp {

    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

        B b = new B();
        b.setName("abc");

        B b1 = new B();
        b1.setName("drilling");
        b1.setPreconditions(Arrays.asList(b));

        A a = new A();
        a.setId("3");
        a.setBs(Arrays.asList(b, b1));

        System.out.println(mapper.writeValueAsString(a));
    }
}

打印:

{
  "id" : "3",
  "bs" : [ {
    "name" : "abc"
  }, {
    "name" : "drilling",
    "preconditions" : [ "abc" ]
  } ]
}