jeudi 17 mai 2018

Storing a JSON of class with a reference to an object of the same class

I have something similar to this:

public class Person {
    public String name;
    public List<Person> family;
}
List<Person> people;

And I want to store people as a JSON string on disk. And I want to follow a good design pattern. Like doing it the right way.

I don't want to end up with

[{"name":"John Doe", "family": [{"name": "Mary", "family": [{"name": "Mary's mother", "family": [{.........

Also one could end up with Mary having John Doe as family too, making a endless recursion.

What I would like to end up is with something like this:

[{"name":"John Doe", "family": [(reference to Mary)]}, {"name": "Mary", "family": [(reference to Mary's Mother), (reference to John Doe)]}, ...]

I don't want to assume the name is unique.

Is adding an "ID" to Person a good implementation/pattern? Because in my class a Person with an ID doesn't make sense (they don't have/need one)

The idea I have in mind (which I think would be a good design pattern) is to have another "private" class

private class PersonWithId extends Person {
    private int id;
}

and store that PersonWithId in the JSON so when storing the family List, i can store the ID as the reference so there is no recursion.

What options do I have?

Thanks.

Aucun commentaire:

Enregistrer un commentaire