如果flutter中的键是数字,如何Map数据

x9ybnkn6  于 2023-02-05  发布在  Flutter
关注(0)|答案(5)|浏览(133)

我得到了一个响应,作为关键字作为数字。如何Map数据为以下响应

{
  "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'];

但我得到错误。帮助如何获得每个变量中每个键的数据
但在Map时,我收到错误,我在UI中添加了部分代码
_message:“类型'Map〈String,dynamic〉'不是类型'List'的子类型”

ve7v8dk2

ve7v8dk21#

下面的方法将把你的JSON字符串转换成一个有效的Map对象,这样你就可以按照你想要的方式得到你的数据。

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
mrphzbgm

mrphzbgm2#

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

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

tvokkenx3#

您得到错误是因为您的数据是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
w46czmvw

w46czmvw4#

请仅使用一个模型“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)';
}
x6yk4ghg

x6yk4ghg5#

从我在您分享的示例响应中看到的,kets都是字符串,应该是......“1”也是字符串FYI。
回到这个错误,你得到它是因为你可能使用变量data1,data2,data3作为一个Map,它不是。
var data1 = data['1'];如果打印此变量,您将获得:

[
    {
      "id": 6,
      "name": "test 1"
    },
    {
      "id": 8,
      "name": "test 2"
    },
    {
      "id": 7,
      "name": "test 3"
    }
  ]

如果要访问id为6且名称为Test 1的子Map,请执行以下操作:

print(data1[0]);

要显示名称:

print(data1[0]["name"]);

相关问题