我有以下模型類。
@JsonSerializable()
class Login {
String? userName;
String? password;
Login({required this.userName, required this.password});
factory Login.fromJson(Map<String, dynamic> json) => _$LoginFromJson(json);
Map<String, dynamic> toJson() => _$LoginToJson(this);
}
生成的零件檔案。
Login _$LoginFromJson(Map<String, dynamic> json) => Login(
userName: json['userName'] as String?,
password: json['password'] as String?,
);
Map<String, dynamic> _$LoginToJson(Login instance) => <String, dynamic>{
'userName': instance.userName,
'password': instance.password,
};
當我嘗試使用它通過以下代碼發布到 api 時
Future<void> loginUser(Login login) async => {
print(login.toJson().toString());
}
列印陳述句的結果(導致轉換錯誤)
{userName: test, password: password}
期望有效的 json 發布是
{
"username": "string",
"password": "string"
}
錯誤資訊
Error: DioError [DioErrorType.other]: Converting object to an encodable object failed: Instance of '_HashSet<String>'
uj5u.com熱心網友回復:
=>從_
Future<void> loginUser(Login login) async => {
print(login.toJson().toString());
}
至
Future<void> loginUser(Login login) async {
print(login.toJson().toString());
}
在第一個示例中,它是一個箭頭函式,其中括號{ }代表一個集合文字,因為它就在箭頭之后,就像在生成的_$LoginToJson函式中一樣,但沒有描述集合的型別。
在第二個示例中,它是一個普通函式,括號{ }定義了函式的主體。
您可能希望呼叫jsonEncode( import dart:convert;) ,它接受一個值,例如 aMap<String, dynamic>并將其轉換為Stringjson 格式的 a 。
更新列印陳述句如下:
print(jsonEncode(login.toJson()));
雖然生成的函式將物件決議為適合 JSON 的格式,但它不會將其轉換為實際的String. 您需要使用jsonEncode. 同樣,在處理 JSON 回應時,您需要jsonDecode回應主體獲取一個Map<String, dynamic>結構,然后您可以將其傳遞給生成的fromJson函式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/483339.html
