如何在dart中解析Map?

qnzebej0  于 2023-05-11  发布在  其他
关注(0)|答案(3)|浏览(135)

我得到了一个格式为

"category1": {
                "Winter": [
                    "Woolen Clothes",
                    "Rain Coats",
                    "sweater"
                ]
            },
            "category2": {
                "Summer": [
                    "Sun Glass",
                    "Cotton Clothes",
                    "Ice Creams"
                ]
            },

如何将其转换为对象。我试过以下方法

Map<String,List<String>> category1;
Map<String,List<String>> category2;

category1:  Map<String,List<String>>.from(json["category1"] ?? [].map((x) => x));
category2:  Map<String,List<String>>.from(json["category2"] ?? [].map((x) => x));

但它会抛出以下错误

type 'MappedListIterable<dynamic, dynamic>' is not a subtype of type 'Map<dynamic, dynamic>'

解析Map的正确方法是什么??

sulc1iza

sulc1iza1#

你应该做的第一件事是创建一个负责MapJSON的模型。我建议你使用这个页面https://app.quicktype.io/。在左侧,你粘贴你想要Map的JSON,在右侧,你选择dart作为生成模型的语言,最后你必须调用那个模型和map中的函数,并将JSON作为参数传递。

// To parse this JSON data, do
    //
    //     final categorias = categoriasFromMap(jsonString);

     import 'package:meta/meta.dart';
     import 'dart:convert';

    class Categorias {
        Category1 category1;
        Category2 category2;

       Categorias({
         required this.category1,
         required this.category2,
     });

         factory Categorias.fromJson(String str) => 
         Categorias.fromMap(json.decode(str));

        String toJson() => json.encode(toMap());

       factory Categorias.fromMap(Map<String, dynamic> json) => Categorias(
           category1: Category1.fromMap(json["category1"]),
           category2: Category2.fromMap(json["category2"]),
       );

        Map<String, dynamic> toMap() => {
          "category1": category1.toMap(),
          "category2": category2.toMap(),
       };
   }

    class Category1 {
       List<String> winter;

       Category1({
    required this.winter,
       });

      factory Category1.fromJson(String str) => 
    Category1.fromMap(json.decode(str));

    String toJson() => json.encode(toMap());

    factory Category1.fromMap(Map<String, dynamic> json) => Category1(
    winter: List<String>.from(json["Winter"].map((x) => x)),
    );

     Map<String, dynamic> toMap() => {
    "Winter": List<dynamic>.from(winter.map((x) => x)),
       };
    }

    class Category2 {
    List<String> summer;

    Category2({
    required this.summer,
    });

    factory Category2.fromJson(String str) => 
    Category2.fromMap(json.decode(str));

    String toJson() => json.encode(toMap());

    factory Category2.fromMap(Map<String, dynamic> json) => Category2(
    summer: List<String>.from(json["Summer"].map((x) => x)),
    );

     Map<String, dynamic> toMap() => {
    "Summer": List<dynamic>.from(summer.map((x) => x)),
       };
   }

    categorias.fromMap(response.data);
9gm1akwq

9gm1akwq2#

import 'dart:convert';

void main() {
  String jsonStr = '''
  {
    "category1": {
        "Winter": [
            "Woolen Clothes",
            "Rain Coats",
            "sweater"
        ]
    },
    "category2": {
        "Summer": [
            "Sun Glass",
            "Cotton Clothes",
            "Ice Creams"
        ]
    }
  }
  ''';

  Map<String, dynamic> jsonMap = json.decode(jsonStr);

  Map<String, Map<String, List<String>>> categories = {};

  jsonMap.forEach((key, value) {
    Map<String, List<String>> items = {};

    value.forEach((innerKey, innerValue) {
      List<String> itemList = [];

      innerValue.forEach((item) {
        itemList.add(item);
      });

      items[innerKey] = itemList;
    });

    categories[key] = items;
  });

  print(categories);
}
9w11ddsr

9w11ddsr3#

import 'dart:convert';

final Map<String, dynamic> json = {
  "category1": {
    "Winter": ["Woolen Clothes", "Rain Coats", "sweater"],
  },
  "category2": {
    "Summer": ["Sun Glass", "Cotton Clothes", "Ice Creams"]
  },
};

final jsonString = jsonEncode(json);

void main() {
  print(jsonString);
  // {"category1":{"Winter":["Woolen Clothes","Rain Coats","sweater"]},"category2":{"Summer":["Sun Glass","Cotton Clothes","Ice Creams"]}}
  
  final jsonParsed = jsonDecode(jsonString);
  final Map<String, List<String>> category1 = Map.fromEntries(
      (jsonParsed["category1"] as Map<String, dynamic>)
          .entries
          .map((e) => MapEntry<String, List<String>>(e.key, (e.value as List<dynamic>).cast()))
  );

  print(category1);
  // {Winter: [Woolen Clothes, Rain Coats, sweater]}
}

相关问题