我必須存盤上次加載的天氣資訊,因此我使用 toJson 方法從天氣物件中獲取 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): ^
我不知道如何解決這個問題......有人可以幫我嗎?
uj5u.com熱心網友回復:
您需要使用 jsonEncode,而不是 toString()。
String jsonString =jsonEncode(_response!.toJson());
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/354857.html
