我试图从云函数中获取一些数据并将其分配给模型。但是我无法使用嵌套数据,我得到以下错误:_TypeError (type '_InternalLinkedHashMap<Object?, Object?>' is not a subtype of type 'Map<String, dynamic>')
我收到的数据如下所示:
{
"answer": "Some optional answer",
"error": "Some optional error",
"usage": { "prompt_tokens": 32, "completion_tokens": 40, "total_tokens": 72 }
}
当我收到数据时,我尝试将其分配给一个模型:
final HttpsCallableResult result = await functions
.httpsCallable('askHW')
.call({'question': userQuestion});
return HWResponse.fromJson(result.data);
HW响应:
class HWResponse {
final String answer;
final String error;
final HWUsage usage;
HWResponse({this.answer = '', this.error = '', required this.usage});
factory HWResponse.fromJson(Map<String, dynamic> json) => HWResponse(
answer: json.containsKey('answer') ? json['answer'] as String : '',
error: json.containsKey('error') ? json['error'] as String : '',
usage:
json["usage"] == null ? HWUsage() : HWUsage.fromJson(json["usage"]),
);
Map<String, dynamic> toJson() => {
"answer": answer,
"error": error,
"usage": usage.toJson(),
};
}
class HWUsage {
final int promptTokens;
final int completionTokens;
final int totalTokens;
HWUsage({
this.promptTokens = 0,
this.completionTokens = 0,
this.totalTokens = 0,
});
factory HWUsage.fromJson(Map<String, dynamic> json) => HWUsage(
promptTokens: json.containsKey('prompt_tokens')
? json['prompt_tokens'] as int
: 0,
completionTokens: json.containsKey('completion_tokens')
? json['completion_tokens'] as int
: 0,
totalTokens:
json.containsKey('total_tokens') ? json['total_tokens'] as int : 0,
);
Map<String, dynamic> toJson() => {
"prompt_tokens": promptTokens,
"completion_tokens": completionTokens,
"total_tokens": totalTokens,
};
}
1条答案
按热度按时间iklwldmw1#
在嵌套字段的
HWResponse
中使用Map<String, dynamic>.from('json['usage]')
似乎是正确的方法,为了避免任何错误,我还使用了json.containsKey('usage')
来确保嵌套字段usage
确实存在。