我使用SQFlite在本地存储数据,我有一个表,其中有一个名为' json‘的字段,此字段属于文本类型,并存储转换为字符串的json,例如:’{姓名:爱德华多,年龄: 23,性别:男性}‘。
到目前为止,一切都很好。
但是,我需要查询数据库中的这些信息,以及它是如何以文本类型的格式存储的,flutter会将其识别为字符串。我不知道如何将它转换回对象。我知道我可以构建一个函数来解决这个问题,前提是存储在json中的信息始终遵循相同的结构。但在我的例子中,json包含的信息将是可变的。
有没有办法解决这个问题?
发布于 2020-11-06 09:19:59
如果你有问题,你的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);发布于 2020-11-06 08:29:15
您可以简单地使用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
https://stackoverflow.com/questions/64707012
复制相似问题