所以我有一个开放的API json响应模型:
{
"object": "list",
"data": [
{
"id": "whisper-1",
"object": "model",
"created": 1677532384,
"owned_by": "openai-internal",
"permission": [
{
"id": "modelperm-KlsZlfft3Gma8pI6A8rTnyjs",
"object": "model_permission",
"created": 1683912666,
"allow_create_engine": false,
"allow_sampling": true,
"allow_logprobs": true,
"allow_search_indices": false,
"allow_view": true,
"allow_fine_tuning": false,
"organization": "*",
"group": null,
"is_blocking": false
}
],
"root": "whisper-1",
"parent": null
},
]
}
下面是数据模型类:
import 'package:flutter_chatgpt/src/data/models/model_model.dart';
class ModelResponse {
ModelResponse({
required this.object,
required this.data,
});
late final String object;
late final List<Model> data;
ModelResponse.fromJson(Map<String, dynamic> json){
object = json['object'];
data = List.from(json['data']).map((e)=>Model.fromJson(e)).toList();
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['object'] = object;
_data['data'] = data.map((e)=>e.toJson()).toList();
return _data;
}
}
class Model {
Model({
required this.id,
required this.object,
});
late final String id;
late final String object;
Model.fromJson(Map<String, dynamic> json){
id = json['id'];
object = json['object'];
}
Map<String, dynamic> toJson() {
final data = <String, dynamic>{};
data['id'] = id;
data['object'] = object;
return data;
}
}
但是在API请求时,当我将数据传递给ModelResponse的fromJson()时,我得到了这个错误:
Exception: Failed to fetch models: type '_Map<String, dynamic>' is not a subtype of type 'String'
看起来像是从API获取响应,但函数无法正确解析JSON并将其转换为对象。我不知道是什么引起的。
2条答案
按热度按时间9o685dep1#
请尝试这个ModelResponse类,基于你的json(从quicktype创建的模型):
然后用途:
atmip9wb2#
将模型类更新为:
然后用途:
生成模型类的链接是Json to Dart Model Class