首页 > 解决方案 > 动态 json 数组的颤振模型

问题描述

所以我有一个 json 文件(模拟数据)。它是这样的:

{
    "data":
    [
        {
            "id": "1",
            "name": "Kacchi Biriyani",
            "videoLink": "https://www.youtube.com/watch?v=K4TOrB7at0Y",
            "author": "Alan Ford",
            "category":"Biriyani",
            "time": "15 min",
            "steps": {
                "step 1": "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
                "step 2": "Suspendisse vel sapien elit"
            },
            "isFavorite": "yes"
        },
        {
            "id": "2",
            "name": "Mughal Biriyani",
            "videoLink": "https://www.youtube.com/watch?v=aNVviTECNM0",
            "author": "Ricky James",
            "category":"Biriyani",
            "time": "10 min",
            "steps": {
                "step 1": "Lorem ipsum dolor sit amet, consectetur adipiscing elit",
                "step 2": "Suspendisse vel sapien elit",
                "step 3": "Proin luctus, quam non dapibus pretium",
                "step 4": "Lorem ipsum dolor sit amet, consectetur adipiscing elit"
            },
            "isFavorite": "yes"
        }

    ]
}

这就是我的模型:

class RecipeModel {
  final String id;
  final String name;
  final String videoLink;
  final String author;
  final String category;
  final String time;
  RecipeModel({
    required this.id,
    required this.name,
    required this.videoLink,
    required this.author,
    required this.category,
    required this.time,
  });

  factory RecipeModel.fromJson(Map<String, dynamic> json) {
    return RecipeModel(
      id: json['id'],
      name: json['name'],
      videoLink: json['videoLink'],
      author: json['author'],
      category: json['category'],
      time: json['time'],
    );
  }
}

现在您可以看到这些步骤:{...} 是动态的,因此对于不同的项目它可能会有所不同。一个项目可以有 5 个步骤,而另一个项目可以有 10 个以上的步骤。

如何在我的模型中为来自 json 的步骤数据编写动态列表?

更新 1:

  List<RecipeModel> recipes = [];
  Future<List<RecipeModel>> getRecipeData() async {
    // var response = await http.get(
    //   Uri.https("jsonplaceholder.typicode.com", 'users'),
    // );
    String response = await DefaultAssetBundle.of(context)
        .loadString('assets/json/recipe.json');
    var result = json.decode(response);

    for (var u in result["data"]) {
      RecipeModel recipe = RecipeModel(
        id: u['id'] ?? "",
        name: u['name'] ?? "",
        videoLink: u['videoLink'] ?? "",
        author: u['author'] ?? "",
        category: u['category'] ?? "",
        time: u['time'] ?? "",
        // steps: u["steps"],
      );
      recipes.add(recipe);
    }

标签: flutterdart

解决方案


使用该方法将步骤映射转换为List<String>类型from


// The steps from your api call.
var json = { "steps": { "step 1": "foo", "step 2": "bar" } }

// Convert the steps from the map to a List.
List<String> steps = List<String>.from(json["steps"].values);

// The result.
steps = ['foo', 'bar']


更新

这就是你的 RecipeModel 应该是什么样子。


class RecipeModel {
  final String id;
  final String name;
  final String videoLink;
  final String author;
  final String category;
  final String time;
  // The dynamic list of steps.
  final List<String> steps;

  RecipeModel({
    required this.id,
    required this.name,
    required this.videoLink,
    required this.author,
    required this.category,
    required this.time,
    // The dynamic list of steps.
    required this.steps,
  });

  factory RecipeModel.fromJson(Map<String, dynamic> json) {
    return RecipeModel(
      id: json['id'],
      name: json['name'],
      videoLink: json['videoLink'],
      author: json['author'],
      category: json['category'],
      time: json['time'],
      // The dynamic list of steps.
      steps: List<String>.from(json['steps'].values),
    );
  }

推荐阅读