Flutter 使用带有 Json 的 SharedPreferences 来存储对象

Flutter using SharedPreferences with Json for storing an object

我必须存储最后加载的天气信息,因此我使用 Json 方法从天气对象中获取 Json 文件:

class WeatherResponse{
  Temperature? temp;
  Weather? weather;
  String? cityName;
  Coordinates? coord;

  WeatherResponse(this.cityName, this.coord);
  WeatherResponse.favWeather(this.coord,this.weather, this.temp, this.cityName);

  Map<String, dynamic> toJson() => {
    "coord": coord!.toJson(),
    "weather": weather!.toJson(),
    "main": temp!.toJson(),
    "name": cityName,
  };

  factory WeatherResponse.fromJson(Map<String, dynamic> json) => WeatherResponse.favWeather(
    Coordinates.fromJson(json["coord"]),
    Weather.fromJson(json['weather']),
    Temperature.fromJson(json["main"]),
    json["name"],
  );

加载我的天气信息后,我将数据存储到 SharedPreferences:


...
WeatherResponse? _response;
...
void _saveToJson() async {
    SharedPreferences pref = await SharedPreferences.getInstance();
    String jsonString =_response!.toJson().toString();

    pref.setString(prefKey, jsonString);

    developer.log('Set to shared preferences: ' + pref.getString(prefKey)!);
  }

保存的值为{coord: {lon: 13.4105, lat: 52.5244}, weather: {description: Mäßig bewölkt, icon: 03d}, main: {temp: 11.41}, name: Berlin} 这是不正确的,因为每个字符串值都缺少 "...正确的输出应如下所示:{"coord": {"lon": 13.4105,"lat": 52.5244},"weather":{"description": "Mäßig bewölkt","icon": "03d"},"main": {"temp": 11.41},"name": "Berlin"} 如果我使用存储的值来获取对象(使用“fromJson”),我会得到以下异常:

response=WeatherResponse.fromJson(json.decode(pref.getString(prefKey)!));
E/flutter ( 4935): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: FormatException: Unexpected character (at character 2)
E/flutter ( 4935): {coord: {lon: 13.4105, lat: 52.5244}, weather: {description: Mäßig bewölkt,...
E/flutter ( 4935):  ^

我不知道如何解决这个问题...有人可以帮我吗?

您需要使用 jsonEncode,而不是 toString()。

String jsonString =jsonEncode(_response!.toJson());