dabadaba dabadaba - 5 months ago 13
JSON Question

Jackson: referencing the same object

There are some cases where the data serialized or unserialized in a body, for example, a JSON body, contains references to the same object. For example, a JSON body with a list of players, and a list of teams composed of these players:

{
"players": [
{ "name": "Player 1" },
{ "name": "Player 2" },
{ "name": "Player 3" },
{ "name": "Player 4" },
{ "name": "Player 5" },
{ "name": "Player 6" },
{ "name": "Player 7" },
{ "name": "Player 8" }
],
"teams": [
{
"name": "Team 1",
"players": [
{ "name": "Player 1"},
{ "name": "Player 2"}
]
},
{
"name": "Team 2",
"players": [
{ "name": "Player 3"},
{ "name": "Player 4"}
]
},
{
"name": "Team 3",
"players": [
{ "name": "Player 5"},
{ "name": "Player 6"}
]
},
{
"name": "Team 4",
"players": [
{ "name": "Player 7"},
{ "name": "Player 8"}
]
}
]
}


As you can imagine Player X refers to the same object, but potentially we could end up with an unwanted scenario where Player X is represented by different objects.

I would like to know what is the best and most common approach to these scenarios. I can think of several ways of doing this:


  1. Add an ID attribute to the
    Player
    class. My design does not include an ID becase it is not needed. The ways of identifying an object are by its reference and if they're contained in a collection, by their position in it (if the collection has positions). This might be considered a bad practice, but I did it intentionally and I don't plan on changing it unless necessary.

  2. Also having a player ID, but instead of serializing/deserializing the teams as a list of players, it would just be a list of IDs. Information contained in the JSON body would be lost, but we would have more compact data.

  3. Sticking to my ID-less design, similarly to the previous point, I could have a list of positions (which in practice would actually be a player ID because they serve as identification means), so the number 0 would refer to the player in the first position in the players list.

  4. Changing the contract and having players with unique name. With this we could now have an ID without having to add a new attribute to the class. However I think it is a bad idea because not necessarily all players should have different names.



What would be the best approach? What is usually done? Do you have different suggestions?

Answer

I went for positioning references. Apparently it is not considered a bad approach necessarily.

So the JSON body would be like this:

{
  "players": [
    { "name": "Player 1" },
    { "name": "Player 2" },
    { "name": "Player 3" },
    { "name": "Player 4" }
  ],
  "teams": [
    [ 3, 1 ],
    [ 0, 2 ]
  ]
}