Jackson JsonMappingException:无限递归(StackOverflowError)

Jackson JsonMappingException: Infinite recursion (StackOverflowError)

我在将对象转换为其等价对象时遇到问题 JSON。

以下是我的 class 结构:

public class Record {
    private byte[] header;
    private String mti;
    private String bitmap;
    private int fieldNumber;
    private String data;
    private String name;
    private String recordType;
    private List<Record> subRecords;
    private Field recordSchema;
    private List<PDSRecord> pdsRecords;
}

在我的例子中,一个记录可以有多个子记录,然后每个子记录可以进一步有多个子记录。因此,我想出了这个模式来存储记录。

我面临的问题是由于 Record class 中 List<Record> 的循环引用。

Jackson 是否可以转换此对象?另外,我需要所有子记录的完整信息。

提前致谢

您可以试试下面的代码。我希望这能解决你的问题。

    try{
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        String value = mapper.writeValueAsString(r3);
        System.out.println(value);
    }catch(IOException a){
        a.printStackTrace();
    }

输出:{ "header": "UEFOS0FK", "mti": "Data", "bitmap": "Name", "fieldNumber": 5, "data": "data", "name": "name", "recordType": "Data", "subRecords": [ { "header": "UEFOS0FK", "mti": "Data", "bitmap": "Name", "fieldNumber": 5, "data": "data", "name": "name", "recordType": "Data", "subRecords": [ { "header": "UEFOS0FK", "mti": "Data", "bitmap": "Name", "fieldNumber": 5, "data": "data", "name": "name", "recordType": "Data", "subRecords": null, "recordSchema": "Record schema", "pdsRecords": [] } ], "recordSchema": "Record schema", "pdsRecords": [] } ], "recordSchema": "Record schema", "pdsRecords": [] }

我能够解决它。为此,我必须为创建的每个对象生成一个唯一的 ID,并将 class 标记为:

@JsonIdentityInfo(
        generator = ObjectIdGenerators.PropertyGenerator.class,
        property = "id")

所以,完整的 class 看起来像这样:

@JsonIdentityInfo(
        generator = ObjectIdGenerators.PropertyGenerator.class,
        property = "id")
@JsonInclude(JsonInclude.Include.NON_NULL)
@Data // Lombok 
public class Record {
    private String id;
    private byte[] header;
    private String mti;
    private String bitmap;
    private int fieldNumber;
    private String data;
    private String name;
    private String recordType;
    @ToString.Exclude // Lombok
    private List<Record> subRecords;
    private Field recordSchema;
    private List<PDSRecord> pdsRecords;

    public Record()
    {
        this.id = UUID.randomUUID().toString();
    }
}

希望对您有所帮助。