flutter json转字符串 字符串转json
一段json字符串
var jsonStr = '{\"errorCode\": \"0\", \"message\": \"成功\", \"data\": { \"id\": 25, \"appLoginUuid\": \"9c64754d293b487aa16fa266bf6aa9cf\", \"userName\": \"111111\", \"nickName\": \"111111\", \"userType\": \"2\", \"mobileNo\": \"11111\", \"status\": \"3\", \"userPhotoUrl\": \"/picture/logo.png\", \"token\": \"5a7913fc62c974c8d8028a2ea58720d0aef07bba496e351744d3767d525456c4\", \"downloadApp\": false } }';
把json字符串转model
//先转json
var json = jsonDecode(jsonStr);
//json转model
var model = UserResModel.fromJson(json);
存储
void _saveUserInfo(UserInfo data) async {
SharedPreferences pref= await SharedPreferences.getInstance();
//将data转换成json字符串
var str = json.encode(data);
pref.setString(DataConst.KEY_UserInfo, str);
_readUserInfo();
}
读取
Future _readUserInfo()async{
SharedPreferences pref= await SharedPreferences.getInstance();
final jsonStr = pref.getString(DataConst.KEY_UserInfo);
print(jsonStr);
print(jsonStr.runtimeType);
if(jsonStr != null && jsonStr.length > 0){
//先将json字符串转json
Map json = jsonDecode(jsonStr);
//将json转model
final model = UserInfo.fromJson(json);
return model;
}
return null;
}