简体   繁体   中英

How can I make instances of a class into a list using a json file

I'm currently creating a Cluedo game and I'm editing the playerpiece class, I have also created a json file called data.json to store data about the playerpiece, for instance: Character Names(eg Colonel Mustard), Weapon etc. I have the following json which I need to convert into list of java objects

{
  "PlayerPieces": {
    "0": "Col Mustard",
    "1": "Prof Plum",
    "2": "Rev Green",
    "3": "Mrs Peacock",
    "4": "Miss Scarlett",
    "5": "Mrs White"
  }
}

At the moment I have a PlayerPiece class and I'm trying to use the string from the data.json to make an instance of PlayerPiece and then add it to the list, something like List<PlayerPieces> , any help or tips on how to get started on the playerpiece class would be greatly, greatly appreciated!

You can use ObjectMapper of 'jackson-databind' library. Below is the sample for converting json file to java objectz

List list = Arrays.asList(objectMapper.readValue(new File("data.json"), PlayerPiecea[].class));

Ref link

ps your data.json file need to be changed to start with json array instead of json object.

you should use HashMap<String, String> with this json:

{
    "0": "Col Mustard",
    "1": "Prof Plum",
    "2": "Rev Green",
    "3": "Mrs Peacock",
    "4": "Miss Scarlett",
    "5": "Mrs White"
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM