Flutter中使用SharedPreferences存储WeatherResponse对象时JSON格式异常问题求助
我一眼就看出问题所在啦!你现在用_response!.toJson().toString()把Map转换成字符串,但这个toString()方法输出的是Dart Map的默认字符串格式,并不是标准的JSON格式——这就是为什么你看到的键都没有双引号,进而导致json.decode解析时抛出FormatException。
解决方案:使用jsonEncode生成标准JSON字符串
Dart的dart:convert库提供了jsonEncode方法,可以将Map安全地序列化为标准JSON格式的字符串。修改你的_saveToJson方法如下:
首先确保导入必要的包:
import 'dart:convert'; import 'dart:developer' as developer; import 'package:shared_preferences/shared_preferences.dart';
然后修改存储逻辑:
void _saveToJson() async { SharedPreferences pref = await SharedPreferences.getInstance(); // 用jsonEncode替代toString(),生成标准JSON字符串 String jsonString = jsonEncode(_response!.toJson()); await pref.setString(prefKey, jsonString); developer.log('Set to shared preferences: ' + pref.getString(prefKey)!); }
为什么这样能解决问题?
jsonEncode会严格按照JSON规范生成字符串,所有键和字符串值都会被双引号包裹,生成的内容就是你期望的标准格式:{"coord": {"lon": 13.4105,"lat": 52.5244},"weather":{"description": "Mäßig bewölkt","icon": "03d"},"main": {"temp": 11.41},"name": "Berlin"}- 之后你用
json.decode(pref.getString(prefKey)!)解析时,就能正常转换成Map,再通过WeatherResponse.fromJson顺利重构对象了。
额外提示
- 建议给
_response加个非空判断,避免空指针异常(比如if (_response != null)再执行存储逻辑); - 存储时加上
await等待setString完成,确保数据成功写入SharedPreferences。
内容的提问来源于stack exchange,提问作者MCB
相关产品推荐
相关产品推荐

