gpt4 book ai didi

flutter - 为什么json序列化器要建模类错误?

转载 作者:行者123 更新时间:2023-12-03 04:42:36 33 4
gpt4 key购买 nike

json

{
"status":1,
"error":"error",
"data":{"id":10000,"email":"xxx@test.com"}
}
数据字段是任意类型的数据
models.dart
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),
);
}
}

user.dart
class User {
int id;
String email;

User({
this.id,
this.email,
});
}
Response resp = Response<User>.formJson(json);
print(resp.status);
print(resp.error);
print(resp.data);
异常(exception)
未处理的异常:类型'_InternalLinkedHashMap '不是类型转换中'用户'类型的子类型
怎么处理呢?
是否需要再次序列化?

最佳答案

json["data"]本质上是Map<String, dynamic>的一种。您的User对象没有隐式转换,因此您必须将该Map显式转换为User。为此,您可以执行基本上与Response的工厂构造函数相同的操作。
User类的更改:

class User {
int id;
String email;

User({
@required this.id,
@required this.email,
});

factory User.fromJson(Map<String, dynamic> json) {
return User(
id: json["id"],
email: json["email"],
);
}
}
Response.formJson的更改:
factory Response.formJson(Map<String, dynamic> json) {
return Response(
status: json["status"] as int,
error: json["error"] as String,
data: User.fromJson(json["data"]), //or T.fromJson is that is a required capability and all your possible T's will have a fromJson constructor
);
}

关于flutter - 为什么json序列化器要建模类错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62927121/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com