我在将对象转换为等效的JSON时遇到问题。
以下是我的课程结构:
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;
}
在我的情况下,一条记录可以具有多个子记录,然后每个子记录可以进一步具有多个子记录。因此,我想出了这种模式来存储记录。
我面临的问题是由于List<Record>
类内的Record
的循环引用。
Jackson是否可以转换此对象?另外,我需要所有子记录的完整信息。
预先感谢
答案 0 :(得分:1)
我能够解决它。为此,我必须为所创建的每个对象生成唯一的ID,并用以下标记该类:
@JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "id")
因此,完整的类如下:
@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();
}
}
希望有帮助。
答案 1 :(得分:0)
您可以尝试以下代码。我希望这能解决您的问题。
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": []
}