If you have the possibility to slightly preprocess your JSON, so that the references are pure int
s, the following approach would be the easiest for you:
@Data
@NoArgsConstructor
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "personId")
public class People {
private int personId;
private String name;
private List<People> friends;
}
A little test for the deserialization:
public class ForwardReferenceTest {
@Test
void forwardReference() throws JsonProcessingException {
String json = "{"people": [
" +
" {
" +
" "personId": 1,
" +
" "name": "An",
" +
" "friends": [2]
" +
" },
" +
" {
" +
" "personId": 2,
" +
" "name": "Bob",
" +
" "friends": [1]
" +
" }
" +
"]}";
Map<String, List<People>> people = new ObjectMapper().readValue(json, new TypeReference<Map<String, List<People>>>() {
});
assertThat(people.get("people").get(1).getFriends().get(0).getPersonId()).isEqualTo(1);
}
}
Could you give this a try?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…