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.

9
  • What is the problem? What makes you say it does not work? How the JSON it generates look like? Commented Aug 25, 2021 at 21:27
  • @stacktrace2234 I need convert map 'variants' to json string, added how it looks and how it should look Commented Aug 25, 2021 at 21:47
  • Did you try 'variants': jsonEncode(this.variants)? Commented Aug 25, 2021 at 21:59
  • @stacktrace2234 I did Commented Aug 25, 2021 at 22:04
  • Isn't this what you try to achieve: i.imgur.com/jiPl3WT.png ? Commented Aug 25, 2021 at 22:10

3 Answers 3

21

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

Sign up to request clarification or add additional context in comments.

1 Comment

my map is without quotes
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;
      }
    }

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.