skip to Main Content

I’m getting a json response in the format

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

How can i convert this to an object. I have tried the following

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));

but it throws the following error

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

what is the correct method to parse the map??

3

Answers


  1. 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]}
    }
    
    Login or Signup to reply.
  2. The first thing you should do is create a model that is in charge of mapping the json. I recommend that you use this page https://app.quicktype.io/.
    on the left side you paste what the json is that you want to map and on the right you choose dart as the language to generate the model,
    r last you must call that model and the function from map and you pass the json as a parameter.

        // 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);
    
    Login or Signup to reply.
  3. 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);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search