I'm trying to parse a remote json but I always get this error _TypeError (type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'String')
, I tried to simplify as much as possible the examples because my model is a bit complex and the JSON has more than 5000 words.
Here's my function:
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);
}
}
My model:
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 example (cut because it's a 5000 words json file):
{"id":"bitcoin","symbol":"btc","name":"Bitcoin", }
CodePudding user response:
I like to modify the entity and use case like
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));
}
And use case
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);