Flutter 为什么json序列化程序到模型类出错? json
数据字段是任意类型的数据 飞镖 代码Flutter 为什么json序列化程序到模型类出错? json,flutter,dart,Flutter,Dart,数据字段是任意类型的数据 飞镖 代码 Response resp=Response.formJson(json); 打印(各自状态); 打印(相应错误); 打印(相应数据); 例外 未处理的异常:类型“\u InternalLinkedHashMap”不是类型转换中“User”类型的子类型 如何处理? 它是否需要再次序列化?json[“数据”]本质上是一种Map类型。没有对用户对象的隐式强制转换,因此必须将映射显式强制转换为用户。要做到这一点,您可以使用与Response的工厂构造函数基本相同
Response resp=Response.formJson(json);
打印(各自状态);
打印(相应错误);
打印(相应数据);
例外
未处理的异常:类型“\u InternalLinkedHashMap”不是类型转换中“User”类型的子类型
如何处理?
它是否需要再次序列化?json[“数据”]
本质上是一种Map
类型。没有对用户
对象的隐式强制转换,因此必须将映射
显式强制转换为用户
。要做到这一点,您可以使用与Response
的工厂构造函数基本相同的方法
对用户
类的更改:
类用户{
int-id;
字符串电子邮件;
使用者({
@需要这个.id,
@需要此电子邮件,
});
factory User.fromJson(映射json){
返回用户(
id:json[“id”],
电子邮件:json[“电子邮件”],
);
}
}
对Response.formJson
的更改:
factory Response.formJson(映射json){
返回响应(
状态:json[“状态”]为int,
错误:json[“error”]作为字符串,
data:User.fromJson(json[“data”]),//或T.fromJson是一个必需的功能,所有可能的T都将有一个fromJson构造函数
);
}
但数据不确定,可能存在其他对象@杰克用User.fromJson(json[“data”]),
查看我在代码行上的评论。您可以使用T
generic,但必须确保每个可能的对象都有一个fromJson
构造函数。这样更好吗??手动转换``var resp=BaseResponse.formJson(json);var user=user.formJson(resp.data);var resp=BaseResponse.formJson(json);var article=Artice.FormJson(分别为数据)```@杰克,只要它们完全一样,就可以了,包括资本化。否则,您可以使用if
语句来检查泛型T
的类型,并使用相应的构造函数,但我认为这种方法更简洁。好的,非常感谢您的回答!!!最后选择手动转换
{
"status":1,
"error":"error",
"data":{"id":10000,"email":"xxx@test.com"}
}
import 'package:flutter/material.dart';
class User {
int id;
String email;
User({
@required this.id,
@required this.email,
});
}
class Response<T> {
final int status;
final String error;
final T data;
const Response({
this.status,
this.error,
this.data,
});
factory Response.formJson(Map<String, dynamic> json) {
return Response(
status: json["status"] as int,
error: json["error"] as String,
data: (json["data"] as T),
);
}
}
Response resp = Response<User>.formJson(json);
print(resp.status);
print(resp.error);
print(resp.data);