我正在尝试从云中解析JSON,收到了数据,
我在stackOverflow上尝试了很多解决方案,但对我没有用,我只是为了熟悉Flutter和Dart而已。
但是我得到了这个错误:
type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<Category>'
这是我的代码:我收到的JSON数据:
{
“totalRowCount”:1,
“pageSize”:100,
“类别”:[{
“CategoryName”:“饮料”,
“CategoryID”:1
}]
}
Services.dart
import 'package:http/http.dart' as http;
import 'Category.dart';
class Services {
static const String url = 'http://example.com/category';
static Future<List<Category>> getCategories() async {
http.Response response = await http.get(url, headers: {"Accept": "application/json"});
if(response.statusCode == 200){
final category = categoryFromJson(response.body);
return category;
} else{
return List<Category>();
}
}
}
Category.dartimport 'dart:convert';
List<Category> categoryFromJson(String str) => List<Category>.from(json.decode(str));
class Category {
Category({
this.totalRowCount,
this.pageSize,
this.categories,
});
final int totalRowCount;
final int pageSize;
final List<CategoryElement> categories;
factory Category.fromJson(Map<String, dynamic> json){
return Category(
totalRowCount: json["totalRowCount"],
pageSize: json["pageSize"],
categories: List<CategoryElement>.from(json["categories"]),
);
}
Map<String, dynamic> toJson() => {
"totalRowCount": totalRowCount,
"pageSize": pageSize,
"categories": List<dynamic>.from(categories.map((x) => x.toJson())),
};
}
class CategoryElement {
CategoryElement({
this.categoryName,
this.categoryId,
});
final String categoryName;
final int categoryId;
factory CategoryElement.fromJson(Map<String, dynamic> json) => CategoryElement(
categoryName: json["CategoryName"],
categoryId: json["CategoryID"],
);
Map<String, dynamic> toJson() => {
"CategoryName": categoryName,
"CategoryID": categoryId,
};
}
任何帮助
最佳答案
您需要在jsonDecode
上调用response.body
,以将响应转换为Map
。
import 'dart:convert';
final category = Category.fromJson(jsonDecode(response.body));
删除以下行,这是导致问题的原因。立即使用工厂对其进行解码,而不是创建另一个函数。该函数无效,因为List.from
接受可迭代,并且您正在提供Map
。另外,json响应不是List
。List<Category> categoryFromJson(String str) => List<Category>.from(json.decode(str));
关于android - 在Dart中从云中解析嵌套的JSON但出现类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64347170/