【问题标题】:How do I create an object List from Json File如何从 Json 文件创建对象列表
【发布时间】:2021-12-05 13:54:04
【问题描述】:

所以我得到了一个“游戏”类,它看起来像这样:

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 ...
      };
}

现在我想创建一个列表,游戏对象在一个 json 文件中:

    { "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 ...

如何将这些数据存储在 List games = [...] 这样的 List 中?我想使用这些数据来填充一些显示这些游戏的卡片。

已经谢谢你了!

【问题讨论】:

    标签: json flutter dart


    【解决方案1】:

    首先,你没有在你的json中显示它,但我希望不同的项目在一个列表中,如果它们不是,那么它不是有效的json。下一个要获得物品,您必须致电jsonDecode

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

    一旦你有了项目列表,把它变成一个游戏列表应该很简单

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

    你也可以在一行中做到这一点,但它更丑:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-06
      • 1970-01-01
      • 1970-01-01
      • 2015-05-07
      • 2019-03-23
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      相关资源
      最近更新 更多