Convert Map to json String flutter
Asked Answered
L

3

5

I am new to dart, trying to convert Map to json String for sqflite, json.encoder and jsonEncode doesn't work. i tried to use json_serializable but couldn't run build_runner, did a bunch of manipulations with meta and analyzer.

the problem occurs when converting Variants, this is should look like:

"variants": {
    "iphone 6": {"1": "8", "2": "6"},
    "xiaomi mi6": {"1": "8", "3": "5"},
    "samsung A6": {"1": "8"}
   }

How it is look like:

 variants: {
    iphone 6: {1: 8, 2: 6},
    xiaomi mi6: {1: 8, 3: 5},
    samsung A6: {1: 8}
   }

SQL func:

Future<void> addToCart(List<List<TextEditingController>> controllers, Item item) async {
     Map<String, Map<int, String>> resultMap = Map();
    var list = item.variants.values.toList();
    var models = item.variants.keys.toList();
    for (int i = 0; list.length > i; i ++) {
      var variantsName = list.elementAt(i).toList();
      var modelsName = models.elementAt(i);
      Map<int, String> values = Map();
      for (int ind = 0; variantsName.length > ind; ind ++) {
        String reasultC = controllers[i].elementAt(ind).text;
        if (reasultC.isNotEmpty && int.parse(reasultC) > 0) {
          values[ind + 1] = reasultC;
        }
      }
      if (!resultMap.containsKey(modelsName) && values.isNotEmpty) {
        resultMap[modelsName] = values;
      }
    }

    db = await openDatabase("$_dbName.db");
    db.execute('''
    CREATE TABLE IF NOT EXISTS $_dbName(
        id INTEGER PRIMARY KEY,
        idItem TEXT,
        title TEXT,
        variants TEXT,
        images TEXT)
    ''');

    var end = Cart(idItem: item.id, title: item.title, variants: resultMap, images: item.images).toJson();
    print(end);
    
    await db.insert(_dbName, end);
    await db.close();
}
class Cart {
  String idItem;
  String title;
  Map<String, dynamic> variants;
  List<String> images;

  Cart({this.idItem, this.title, this.variants, this.images});

  Map<String, dynamic> toJson() =>
      <String, dynamic>{
        'idItem': this.idItem,
        'title': this.title,
        'variants': jsonEncode(this.variants), <= NoSuchMethodError: Class '_InternalLinkedHashMap<int, String>' has no instance method 'toJson'. Receiver: _LinkedHashMap len:1 T
        'images': json.encode(this.images)
      };
}

Thanks.

Labialize answered 25/8, 2021 at 21:11 Comment(9)
What is the problem? What makes you say it does not work? How the JSON it generates look like?Ameline
@Ameline I need convert map 'variants' to json string, added how it looks and how it should lookLabialize
Did you try 'variants': jsonEncode(this.variants)?Ameline
@Ameline I didLabialize
Isn't this what you try to achieve: i.imgur.com/jiPl3WT.png ?Ameline
@Ameline is itLabialize
I get error when use encode: NoSuchMethodError: Class '_InternalLinkedHashMap<int, String>' has no instance method 'toJson'. Receiver: _LinkedHashMap len:1 TLabialize
Edit the question with the new code.Ameline
@Ameline I did itLabialize
L
1

I found an error and it is a very childish error, changed the map type from Map <String, Map <int, String> to Map <String, Map <String, String >>

Map<String, Map<String, String>> resultMap = Map();
    var list = item.variants.values.toList();
    var models = item.variants.keys.toList();
    for (int i = 0; list.length > i; i ++) {
      var variantsName = list.elementAt(i).toList();
      var modelsName = models.elementAt(i);
      Map<String, String> values = Map();
      for (int ind = 0; variantsName.length > ind; ind ++) {
        String reasultC = controllers[i].elementAt(ind).text;
        if (reasultC.isNotEmpty && int.parse(reasultC) > 0) {
          values["${ind + 1}"] = reasultC;
        }
      }
      if (!resultMap.containsKey(modelsName) && values.isNotEmpty) {
        resultMap[modelsName] = values;
      }
    }
Labialize answered 26/8, 2021 at 8:55 Comment(0)
L
18

This is working correctly with json.encode:

import 'dart:convert';

void main() {
  try {
    var obj = {
      "variants": {
        "iphone 6": {"1": "8", "2": "6"},
        "xiaomi mi6": {"1": "8", "3": "5"},
        "samsung A6": {"1": "8"}
      }
    };
    String str = json.encode(obj);
    print(str);
  } catch(e) {
    print(e);
  }
}

DartPad link

Loverly answered 26/8, 2021 at 2:0 Comment(1)
my map is without quotesLabialize
L
1

I found an error and it is a very childish error, changed the map type from Map <String, Map <int, String> to Map <String, Map <String, String >>

Map<String, Map<String, String>> resultMap = Map();
    var list = item.variants.values.toList();
    var models = item.variants.keys.toList();
    for (int i = 0; list.length > i; i ++) {
      var variantsName = list.elementAt(i).toList();
      var modelsName = models.elementAt(i);
      Map<String, String> values = Map();
      for (int ind = 0; variantsName.length > ind; ind ++) {
        String reasultC = controllers[i].elementAt(ind).text;
        if (reasultC.isNotEmpty && int.parse(reasultC) > 0) {
          values["${ind + 1}"] = reasultC;
        }
      }
      if (!resultMap.containsKey(modelsName) && values.isNotEmpty) {
        resultMap[modelsName] = values;
      }
    }
Labialize answered 26/8, 2021 at 8:55 Comment(0)
A
1

you can simply use this function

String MapToJson(List<Map<String, dynamic>> map) {
   String res = "[";

  for (var s in map) {
   res += "{";

    for (String k in s.keys) {
     res += '"';
  res += k;
  res += '":"';
  res += s[k].toString();
  res += '",';
}
res = res.substring(0, res.length - 1);

res += "},";
res = res.substring(0, res.length - 1);
  }

 res += "]";

 return res;
   }
Amedeo answered 30/5, 2022 at 17:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.