Home > other >  How do I create an object List from Json File
How do I create an object List from Json File

Time:10-19

So I got a class "Game", it looks like that:

Game gameFromJson(String str) => Game.fromJson(json.decode(str));
String gameToJson(Game data) => json.encode(data.toJson());

class Game {
  Game({
    required this.gameCategory,
    required this.gameName,
    required this.playerNumber,
    required this.gameDuration,
    // and more ..
  });

  String gameCategory;
  String gameName;
  String playerNumber;
  String gameDuration;
  // and more ...

  factory Game.fromJson(Map<String, dynamic> json) => Game(
        gameCategory: json["gameCategory"],
        gameName: json["gameName"],
        explanations: List<String>.from(
          json["explanations"].map((x) => x),
        ),
        // and more ...
      );

  Map<String, dynamic> toJson() => {
        "gameCategory": gameCategory,
        "gameName": gameName,
        // and more ...
      };
}

And now I want to create a list, the game objects are in a json File:

    { "gameCategory": "Kaum Material",
    "gameName": "game1",
    "playerNumber": "2 - 10",
    "gameDuration": "10 - 25 Minuten",
    "materials": "Getränke",
    "funFactor": "0.5",
    "drunknessFac": "0.4",
    "difficulty": "0.3",
    "dirtyFactor": "1",
    "explanations": [
        "explanation1.",
        "explanation2.",
        "explanation3.",
        "explanation4“."
    ],
    "imagePath": "./assets/images/games/game1.jpg"
  },
  { "gameCategory": "Kaum Material",
    "gameName": "game2",
    "playerNumber": "2 - 10",
    "gameDuration": "5 - 20 Minuten",
// 10 more objects like this are following ...

How can I store that data in a List like List games = [...]? I want to use that data to fill some cards that show those games.

Thank you already!

CodePudding user response:

First of all, you didn't show it in your json, but I hope the different items are within a list, if they aren't, then it isn't valid json. Next In order to get the items, you must call jsonDecode

final List<dynamic> items = jsonDecode(fileContents);

once you have the list of items, turning it into a list of Games should be really simple

List<Game> games = items.map((item) => Game.fromJson(item as Map<String, dynamic>);

You could also do this in a single line, but it is uglier:

List<Game> games = 
  (jsonDecode(fileContents) as List)
    .map((item) => Game.fromJson(item as Map<String, dynamic>);
  • Related