如果键是颤振中的数字,如何映射数据

时间:2020-12-20 16:09:22

标签: flutter dart

您好,我收到了与 numeric 一样关键的回复。如何为以下响应映射数据

{
  "1": [
    {
      "id": 6,
      "name": "test 1"
    },
    {
      "id": 8,
      "name": "test 2"
    },
    {
      "id": 7,
      "name": "test 3"
    }
  ],
  "2": [
    {
      "id": 9,
      "name": "ttt1"
    },
    {
      "id": 5,
      "name": "ttt3"
    }
  ],
  "3": [
    {
      "id": 4,
      "name": "ttg",
      "status_id": 1
    }
  ]
}

这是我的模型

import 'dart:convert';

Map<String, List<HomeBannerModel>> homeBannerModelFromJson(String str) => Map.from(json.decode(str)).map((k, v) => MapEntry<String, List<HomeBannerModel>>(k, List<HomeBannerModel>.from(v.map((x) => HomeBannerModel.fromJson(x)))));

String homeBannerModelToJson(Map<String, List<HomeBannerModel>> data) => json.encode(Map.from(data).map((k, v) => MapEntry<String, dynamic>(k, List<dynamic>.from(v.map((x) => x.toJson())))));
class HomeBannerModel {
  int id;
  String name;


  HomeBannerModel({this.id, this.name});

  HomeBannerModel.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    name= json['name'];
 
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['name'] = this.name;
    return data;
  }
}

我需要将 ui 中的值作为

 var data1 = data['1'];
var data2= data['2'];
var data3= data['3'];

但是我遇到了错误。求助如何获取每个变量中每个key的数据

但是在映射时出现错误,我在 UI 中添加了部分代码

_message:"type 'Map' 不是类型 'List' 的子类型"

4 个答案:

答案 0 :(得分:0)

以下方法会将您的 json 字符串转换为有效的地图对象,以便您可以按照自己的方式获取数据。

Map<String, List<HomeBannerModel>> homeBannerModelFromJson(String str) => Map.from(json.decode(str)).map((k, v) => MapEntry<String, List<HomeBannerModel>>(k, List<HomeBannerModel>.from(v.map((x) => HomeBannerModel.fromJson(x)))));

访问数据

final data = homeBannerModelFromJson(your_json_string);
print(data['1'][0].name); // test 1

答案 1 :(得分:0)

您当前的 json 结构是 Map<String, List<Map<String, dynamic>>> 你可以尝试类似

var json = {...};
json.forEach((key, list) {
    list.forEach((homeBannerModelMap) {
        HomeBannerModel hBM = HomeBannerModel.fromJson(homeBannerModelMap);
    });
});

答案 2 :(得分:0)

您收到错误是因为您的数据是 Map 类型,而不是 List。 所以你可以做这样的事情:

// [data] is result banners
List data = []; 

// [result] is your object variable {"1": [{"id": 1, "name": "Welcome!"}]} etc
// So .forEach method is used for iterating through your json object

result.forEach((k, v){

  // in which iteration I will map every instance to List of [HomeBannerModel]
  
  var value = v.map((banner) => HomeBannerModel.fromJson(banner)).toList();

  //in result I will add the result to our [banners] List

  data.add(value);
});

但在这种情况下,你应该这样做:

data1 = data[1] // use int as the key, result will be List of BannerModels [Instance of 'HomeBannerModel', Instance of 'HomeBannerModel']

代替:

var data1 = data['1']; //use string as the key

答案 3 :(得分:0)

请仅使用一个模型“HomeBannerModel”尝试以下代码。

main() {
  final Map<String, dynamic> json = {
    "1": [
      {"id": 6, "name": "test 1"},
      {"id": 8, "name": "test 2"},
      {"id": 7, "name": "test 3"}
    ],
    "2": [
      {"id": 9, "name": "ttt1"},
      {"id": 5, "name": "ttt3"}
    ],
    "3": [
      {"id": 4, "name": "ttg", "status_id": 1}
    ]
  };

  final Map datas = {};
  json.forEach((key, value) {
    datas.addAll(
        {"$key": value.map((ele) => HomeBannerModel.fromMap(ele)).toList()});
  });

  print(datas["1"]);
  print(datas["2"]);
  print(datas["3"]);
}

class HomeBannerModel {
  final int id;
  final String name;
  final int status_id;
  HomeBannerModel({
    this.id,
    this.name,
    this.status_id,
  });

  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'name': name,
      'status_id': status_id,
    };
  }

  factory HomeBannerModel.fromMap(map) {
    if (map == null) return null;

    return HomeBannerModel(
      id: map['id'],
      name: map['name'],
      status_id: map['status_id'],
    );
  }

  @override
  String toString() => 'Details(id: $id, name: $name, status_id: $status_id)';
}

您也可以尝试使用两个模型 (1) Data 和 (2) HomeBannerModel。请查看以下代码:

main() {
  final Map<String, dynamic> json = {
    "1": [
      {"id": 6, "name": "test 1"},
      {"id": 8, "name": "test 2"},
      {"id": 7, "name": "test 3"}
    ],
    "2": [
      {"id": 9, "name": "ttt1"},
      {"id": 5, "name": "ttt3"}
    ],
    "3": [
      {"id": 4, "name": "ttg", "status_id": 1}
    ]
  };

  final List<Data> data = [];
  json.forEach((key, value) {
    data.add(Data.fromMap({"id": key, "details": value}));
  });

  print(data.firstWhere((e) => e.dataID == '1').homeBannerModel);
  print(data.firstWhere((e) => e.dataID == '2').homeBannerModel);
  print(data.firstWhere((e) => e.dataID == '3').homeBannerModel);
}

class Data {
  final String dataID;
  final List<HomeBannerModel> homeBannerModel;
  Data({
    this.dataID,
    this.homeBannerModel,
  });

  factory Data.fromMap(Map<String, dynamic> map) {
    if (map == null) return null;
    return Data(
        dataID: map["id"],
        homeBannerModel: (map["details"]
            .map<HomeBannerModel>((ele) => HomeBannerModel.fromMap(ele))
            .toList() as List<HomeBannerModel>));
  }

  @override
  String toString() => 'Data(id: $dataID, details: $homeBannerModel)';
}

class HomeBannerModel {
  final int id;
  final String name;
  final int status_id;
  HomeBannerModel({
    this.id,
    this.name,
    this.status_id,
  });

  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'name': name,
      'status_id': status_id,
    };
  }

  factory HomeBannerModel.fromMap(map) {
    if (map == null) return null;

    return HomeBannerModel(
      id: map['id'],
      name: map['name'],
      status_id: map['status_id'],
    );
  }

  @override
  String toString() => 'Details(id: $id, name: $name, status_id: $status_id)';
}