简体   繁体   English

Flutter dart 处理 json

[英]Flutter dart handling json

How can I map this data in flutter/ dart如何在 flutter/dart 中映射此数据

[{
  "Genesis": {
  "1": "31",
  "2": "25",
  "3": "24",
  "4": "26",
  "5": "32",
  "6": "22",
  "7": "24",
  "8": "22",
  "9": "29",
  ...},
"Exodus":{
  "1": "22",
  "2": "25",
  "3": "22",
  "4": "31",
  "5": "23",
  "6": "30",
  "7": "25",
  "8": "32",
  "9": "35",
  "10": "29",
  "11": "10",
  "12": "51",
 ....} ...}]

Working with Bible JSON, I would like to get the words store them under string book, then store the keys in a list called chapters (for now not so interested in the value) only interested in how I can get the book and chapter from this JSON使用 Bible JSON,我想让单词将它们存储在 string book 下,然后将键存储在名为 Chapters 的列表中(现在对值不那么感兴趣)只对我如何从中获取这本书和章节感兴趣JSON

How to encode and decode json: https://dart.dev/guides/libraries/library-tour#decoding-and-encoding-json如何编码和解码 json: https : //dart.dev/guides/libraries/library-tour#decoding-and-encoding-json

I've created a simple example, how you can reach each element:我创建了一个简单的示例,说明如何访问每个元素:

final sourceList = [{
  "Genesis": {
  "1": "31",
  "2": "25",
  "3": "24",
  "4": "26",
  "5": "32",
  "6": "22",
  "7": "24",
  "8": "22",
  "9": "29",
  },
"Exodus":{
  "1": "22",
  "2": "25",
  "3": "22",
  "4": "31",
  "5": "23",
  "6": "30",
  "7": "25",
  "8": "32",
  "9": "35",
  "10": "29",
  "11": "10",
  "12": "51",
 }}];
  
  final sourceMap = sourceList.first; // If sourceList.length == 1, otherwise you can iterate throught the list - https://api.dart.dev/stable/2.9.2/dart-core/Iterable/forEach.html
  
  final books = sourceMap.keys; // If sourceList.length > 1, then do it inside forEach
  
  for (var book in books) {
    print(book);
    print(sourceMap[book]);
  }
  
  //You can do whatever you need - print(sourceMap['Exodus']['4']); prints `31`

Maybe use the map for this JSON so if your JSON grows, you should use the list for complex search.也许使用这个 JSON 的映射,所以如果你的 JSON 增长,你应该使用列表进行复杂的搜索。

You can use like this:你可以这样使用:

final model = books.firstWhere((item) => item.name == name);

If I were, I create a book model and I would fill model in JSON file.如果是,我会创建一个书籍模型,然后将模型填充到 JSON 文件中。

class BookModel {
  String name;
  Book book;
  BookModel(this.name, this.book);
}

And I created a sample to use in a flutter, look at this.我创建了一个样本用于颤振,看看这个。 Book Models Sample 书籍模型样本

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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