【问题标题】:Flutter: Convert string to MapFlutter:将字符串转换为地图
【发布时间】:2025-12-30 00:50:06
【问题描述】:

我正在使用 SQFlite 在本地存储数据,我有一个表,其中有一个名为 'json' 的字段,该字段是 TEXT 类型并存储一个转换为字符串的 json,例如:'{name: Eduardo,年龄:23​​,性别:男}'。

到目前为止,一切正常。

但是我需要从数据库中查阅这些信息,以及它是如何以文本类型格式存储的,flutter 将其识别为字符串。我不知道如何将其转换回对象。 我知道我可以构建一个函数来解决这个问题,以防json中存储的信息始终符合相同的结构。但在我的情况下,json 包含的信息将是可变的。

有没有办法解决这个问题?

【问题讨论】:

    标签: json sqlite flutter sqflite


    【解决方案1】:

    您可以简单地使用 dart:convert 包中的 json.decode 函数。

    示例:

    
    import 'dart:convert';
    
    main() {
      final jsonString = '{"key1": 1, "key2": "hello"}';
      final decodedMap = json.decode(jsonString);
    
      // we can now use the decodedMap as a normal map
      print(decodedMap['key1']); 
    }
    
    

    查看这些链接了解更多详情

    https://api.dart.dev/stable/2.10.3/dart-convert/json-constant.html

    https://api.dart.dev/stable/2.4.0/dart-convert/dart-convert-library.html

    【讨论】:

    • 我已经试过了,但我的问题是我的字符串在键中没有引号,所以这个函数会抛出“发现意外字符”错误
    • @EduardoColon 请看一下我写的新答案,我对其进行了测试并且它有效,代码将未引用的字符串替换为带引号的字符串,然后轻松使用它们
    • 这行不通,因为字符串没有引号..
    【解决方案2】:

    如果您的 json 键没有引号,请尝试此代码,它将未加引号的字符串转换为带引号的字符串,然后对其进行解码,这是 100% 的工作

    
    
    
    final string1 = '{name : "Eduardo", numbers : [12, 23], country: us }';
    
    // remove all quotes from the string values
    final string2=string1.replaceAll("\"", "");
    
    // now we add quotes to both keys and Strings values
    final quotedString = string2.replaceAllMapped(RegExp(r'\b\w+\b'), (match) {
      return '"${match.group(0)}"';
    });
    
    // decoding it as a normal json
      final decoded = json.decode(quotedString);
      print(decoded);
    
    

    【讨论】: