2

We transform incoming data (in JSON, but it could be XML or anything) into immutable Java objects using the simplest method:

// pseudocode

Npc[] npcs;
for (jsonNPC : jsonNPCs) {

   Quest[] quests;
   for (jsonQuest : jsonNPC.quests) {
      quests.add(new Quest(jsonQuest.get(foo), jsonQuest.get(bar), ...));
   }

   npcs.add(new Npc(jsonNPC.get(name), quests, ...));

}

This works fine, but it gets more complex. We now want to make quests refer to other Quest instances as their "prerequisite quests".

The problem is, a referred quest might only be parsed after the referring quest has been constructed (the input data is not ordered, nor could it be, since there may be bidirectional references between NPCs). That means we can't attach it at construction time. But because Quest is immutable, we have to.

How is such a problem usually solved?

(Note: There are no circular references. That should help, I think)

1 Answer 1

1

If a prerequisite quests are always placed in the json string before the quests that need those, you could simply add a questID and a prerequisiteQuestID field and store all parsed quests ordered by their ids. If a prerequisiteQuestID occurs, you can chose the quest from the list.

If the quests are not ordered, you have to store them temporarily. Design a mutable class that holds the data, fill it, and in the end, create real Quest objects for all those quests and add them to the definite list.

Sign up to request clarification or add additional context in comments.

3 Comments

"If the quests are not ordered" - That is the case. A temporary graph could work though.
Which json parser do you use? I'm happy with google gson which fills private fields of an object with the json data. Therefore, you should always create your own json-data holding class because you can't rely on other classes' private fields. I would simply let gson parse the json into a structure of my own classes and then walk through these and create the needed objects.
The JSON data is too complex for Gson. It contains references that need to be resolved, type parameters that need to be transformed to different classes, etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.