vs_lala
vs_lala

Reputation: 745

Jackson JsonMappingException: Infinite recursion (StackOverflowError)

I have a problem converting the object into its equivalent JSON.

Following is my class structure:

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;
}

In my case, a record can have multiple sub-records and then each sub-record can further have multiple sub-records. Therefore, I came up with this schema to store the records.

The problem I'm facing is due to the Circular Reference of List<Record> inside Record class.

Is there anyway Jackson could convert this object? Also, I would need the complete information of all the sub-records.

Thanks in advance

Upvotes: 2

Views: 9114

Answers (2)

vs_lala
vs_lala

Reputation: 745

I was able to solve it. For this, I had to generate a unique Id for every object that is created and mark the class with:

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

So, the complete class looks like this:

@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();
    }
}

Hope it helps.

Upvotes: 4

CodeRider
CodeRider

Reputation: 582

You can try the below code. I hope this solves your problem.

    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();
    }

Output:{ "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": [] }

Upvotes: -2

Related Questions