Ad

Flutter Using SharedPreferences With Json For Storing An Object

- 1 answer

I have to store the last loaded weather information, therefor I use toJson Method to get a Json-file out of the weather-object:

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"],
  );

after loading my weather information I store the data to 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)!);
  }

the saved value is {coord: {lon: 13.4105, lat: 52.5244}, weather: {description: Mäßig bewölkt, icon: 03d}, main: {temp: 11.41}, name: Berlin} this is not correct, because of missing " at every string value... the correct output should look like this: {"coord": {"lon": 13.4105,"lat": 52.5244},"weather":{"description": "Mäßig bewölkt","icon": "03d"},"main": {"temp": 11.41},"name": "Berlin"} If I use the stored value to get the object (with "fromJson") I get following exception:

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):  ^

I don't know how to fix this... Can anyone help me please?

Ad

Answer

You need to use jsonEncode, not toString().

String jsonString =jsonEncode(_response!.toJson());
Ad
source: stackoverflow.com
Ad