Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
239 views
in Technique[技术] by (71.8m points)

java - How to handle forward references during JSON deserialisation?

I have to parse a JSON like this in Jackson:

"people": [
    {
        "personId": 1,
        "name": "An",
        "friends": [{"personId": 2}]
    },
    {
        "personId": 2,
        "name": "Bob",
        "friends": [{"personId": 1}]
    }
]

This should result in An's friends array containing Bob, and Bob's friends array containing An. I'm using this decorator on the Person class:

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

The problem is that, during deserialisation, Jackson sets the first person in An's friends to null, as Bob hasn't been parsed yet. What's the best way to work around this?

question from:https://stackoverflow.com/questions/65909475/how-to-handle-forward-references-during-json-deserialisation

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you have the possibility to slightly preprocess your JSON, so that the references are pure ints, 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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...