将 Map 转换为 json 字符串 flutter

Convert Map to json String flutter

我是 dart 的新手,尝试将 Map 转换为 sqflite 的 json 字符串,json.encoderjsonEncode 不起作用。我尝试使用 json_serializable 但不能 运行 build_runner,用 meta 和分析器做了一堆操作。

转换变体时出现问题,这应该是这样的:

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

它的样子:

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

SQL 函数:

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

谢谢。

这与 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

我发现了一个错误,这是一个非常幼稚的错误,将地图类型从 Map <String, Map <int, String> 更改为 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;
      }
    }

你可以简单地使用这个功能

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