-1

I'm making a json file where I will store data for multiple players in a game. Since I obviously don't want duplicates of the same player , I want to check if the player is already registered in the json file by looking for his/hers name. What's the best way of going about doing this? I only need to know if the player is mentioned, not where or how many thimes.

Sorry if this is a simple task, I'm quite new to java. Any help is appreciated!

keenest
  • 55
  • 6

2 Answers2

0

I'd suggest treating JSON only as a format for storage, if you really need it to persist it e.g. between game sessions. Once you have the JSON, load it to some object and perform any check on such object.

For example, having such JSON:

{
  players: ["John Doe", "Alice", "Bob"]
}

you can deserialize it to such Java class instance (it's a separate problem how to do it):

class GameSettings {
    Set<String> playerNames; // Set to express that no duplicates can appear.
}

and when registering a new player, check if it already exists by calling:

gameSettings.playerNames.contains("New player name")
PiotrK
  • 1,502
  • 1
  • 15
  • 33
0

Imagine you have the following JSON:

{
  "players": [
    {
      "username": "john"
    },
    {
      "username": "mary"
    },
    {
      "username": "karl"
    }
  ]
}

PS: Inside player object you can add as many fields as you want :)

Let's try doing a possible procedure:

  1. Read the JSON file with a suited library. See this for more help.
  2. Cycle the players array and store every username (or player object) in a HashSet (more here).
  3. To check if a player already exists call the hashset method contains. HashSet contains has O(1) expected time so "is super fast" (more here).

Hope it helps :)

Carlo Corradini
  • 2,927
  • 2
  • 18
  • 24