所以我得到了一個“游戲”類,它看起來像這樣:
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 = [...] 之類的串列中?我想用這些資料來填充一些顯示這些游戲的卡片。
已經謝謝了!
uj5u.com熱心網友回復:
首先,你沒有在你的 json 中顯示它,但我希望不同的專案在一個串列中,如果它們不是,那么它不是有效的 json。Next 為了得到物品,你必須呼叫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>);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/324337.html
上一篇:我需要拆分json資料
下一篇:創建自定義動態JSON字串
