Jackson Annotation创建本地JSON参考

问题描述 投票:1回答:1

我有以下类结构

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"
        }
    ]
}
java json jackson jersey-2.0
1个回答
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" ]
  } ]
}
© www.soinside.com 2019 - 2024. All rights reserved.