我试图解析一个远程json,但是我总是得到这个错误_TypeError (type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'String'),我试图尽可能地简化示例,因为我的模型有点复杂,而且JSON有5000多个单词。
这是我的功能:
Future<void> updateCrypto(String symbol) async {
Uri url = Uri.https(); // url where I get the json
try {
final response = await http.get(url);
final parsedJson = json.decode(response.body) as Map<String, dynamic>;
final Cryptocurrency updatedCrypto = Cryptocurrency.fromJson(parsedJson);
} catch (error) {
throw (error);
}
}我的模特:
class Cryptocurrency with ChangeNotifier {
Cryptocurrency({
required this.id,
required this.symbol,
required this.name,
...
});
late final String id;
late final String symbol;
late final String name;
...
factory Cryptocurrency.fromJson(Map<String, dynamic> json) {
return Cryptocurrency(
id: json['id'],
symbol: json['symbol'],
name: json['name'],
...
}
}Json示例(因为它是一个5000字的json文件):
{"id":"bitcoin","symbol":"btc","name":"Bitcoin", }发布于 2022-08-11 09:17:51
我喜欢修改实体和用例,如
import 'dart:convert';
class Cryptocurrency with ChangeNotifier {
final String id;
final String symbol;
final String name;
Cryptocurrency({
required this.id,
required this.symbol,
required this.name,
});
Map<String, dynamic> toMap() {
final result = <String, dynamic>{};
result.addAll({'id': id});
result.addAll({'symbol': symbol});
result.addAll({'name': name});
return result;
}
factory Cryptocurrency.fromMap(Map<String, dynamic> map) {
return Cryptocurrency(
id: map['id'] ?? '',
symbol: map['symbol'] ?? '',
name: map['name'] ?? '',
);
}
String toJson() => json.encode(toMap());
factory Cryptocurrency.fromJson(String source) =>
Cryptocurrency.fromMap(json.decode(source));
}用例
final response = await http.get(Uri.parse(url));
final parsedJson = json.decode(response.body);
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
final Cryptocurrency updatedCrypto = Cryptocurrency.fromJson(data);https://stackoverflow.com/questions/73317643
复制相似问题