我是扑扑的新手。我正在尝试通过以下代码从api获取json:
final response = await http.get(url, headers: {
'Content-Type': 'application/json; charset=utf-8',
});
print((json.decode(response.body)['categories'] as List)
.map((data) => CategoryModel.fromJson(data))
.toList());
final responseJson = (json.decode(response.body)['categories'] as List)
.map((data) => CategoryModel.fromJson(data))
.toList();
return responseJson;
但是我不能反序列化它。 这是我得到的错误:
I/flutter (19749): NoSuchMethodError: The method '[]' was called on null.
I/flutter (19749): Receiver: null
I/flutter (19749): Tried calling: []("products")
CategoryModel:
import 'package:pbl_store/models/cat_assoc.dart';
class CategoryModel{
String id;
String relationShipId;
String name;
String idParent;
String levelDept;
String numberProductRecursive;
String active;
CatAsso associationModel;
CategoryModel({this.id, this.name, this.idParent, this.relationShipId,
this.levelDept, this.associationModel, this.numberProductRecursive, this.active});
factory CategoryModel.fromJson(Map<String, dynamic> parsedJson) {
return CategoryModel(
id: parsedJson['id'].toString(),
name: parsedJson['name'] ,
idParent: parsedJson['id_parent'],
levelDept: parsedJson['level_depth'],
active: parsedJson['active'],
numberProductRecursive: parsedJson['nb_products_recursive'].toString(),
associationModel: CatAsso.fromJson(parsedJson['associations'])
);
}
}
ProductInCategory:
class ProductInCategory{
String id;
ProductInCategory({this.id});
factory ProductInCategory.fromJson(Map<String, dynamic> parsedJson){
return ProductInCategory(
id: parsedJson['id'].toString()
);
}
}
CatAsso:
import 'package:pbl_store/models/product_in_category.dart';
class CatAsso{
List<ProductInCategory> filterPs;
CatAsso({this.filterPs});
factory CatAsso.fromJson(Map<String, dynamic> parsedJson) {
var product = parsedJson['products'];
List<ProductInCategory> filteredProductList = List();
if(product != null){
filteredProductList = List<ProductInCategory>.from(product.map<ProductInCategory>((i) => ProductInCategory.fromJson(i)));
}
return CatAsso(
filterPs: filteredProductList
);
}
}
在每个类别中,都有子类别的ID和产品的ID。我想要产品ID。 这是我要获取的json:
{
"categories": [
{
"id": 2,
"id_parent": "1",
"level_depth": "1",
"nb_products_recursive": "162",
"active": "1",
"id_shop_default": "1",
"is_root_category": "1",
"position": "0",
"date_add": "2018-12-31 09:52:57",
"date_upd": "2018-12-31 09:52:57",
"name": "Home",
"link_rewrite": "home",
"description": "",
"meta_title": "",
"meta_description": "",
"meta_keywords": "",
"associations": {
"categories": [
{
"id": "3"
},
{
"id": "4"
},
{
"id": "5"
}
],
"products": [
{
"id": "8"
},
{
"id": "13"
},
{
"id": "14"
},
{
"id": "17"
},
{
"id": "18"
},
{
"id": "19"
},
{
"id": "125"
},
{
"id": "126"
},
{
"id": "127"
},
{
"id": "128"
},
{
"id": "129"
},
{
"id": "130"
},
{
"id": "131"
},
{
"id": "132"
},
{
"id": "133"
},
{
"id": "134"
},
{
"id": "135"
},
{
"id": "136"
},
{
"id": "137"
},
{
"id": "138"
},
{
"id": "139"
},
{
"id": "140"
},
{
"id": "141"
},
{
"id": "142"
},
{
"id": "143"
},
{
"id": "145"
},
{
"id": "146"
},
{
"id": "147"
},
{
"id": "148"
},
{
"id": "149"
},
{
"id": "150"
},
{
"id": "151"
},
{
"id": "152"
},
{
"id": "153"
},
{
"id": "154"
},
{
"id": "156"
},
{
"id": "157"
},
{
"id": "158"
},
{
"id": "159"
},
{
"id": "160"
},
{
"id": "161"
},
{
"id": "162"
},
{
"id": "163"
},
{
"id": "164"
},
{
"id": "165"
},
{
"id": "166"
},
{
"id": "167"
},
{
"id": "168"
},
{
"id": "169"
},
{
"id": "170"
},
{
"id": "171"
},
{
"id": "172"
},
{
"id": "173"
},
{
"id": "174"
},
{
"id": "175"
},
{
"id": "178"
},
{
"id": "179"
},
{
"id": "180"
},
{
"id": "181"
},
{
"id": "182"
},
{
"id": "183"
},
{
"id": "184"
},
{
"id": "185"
},
{
"id": "186"
},
{
"id": "187"
},
{
"id": "188"
},
{
"id": "189"
},
{
"id": "190"
},
{
"id": "191"
},
{
"id": "192"
},
{
"id": "193"
},
{
"id": "195"
}
]
}
}
]
}
请向我解释为什么会出现此问题,并帮助我找到解决方法...。
答案 0 :(得分:0)
尝试一下
Future <CategoryModel> getCategories() async {
try {
final response = await http.get(url ,
headers: {
'Content-Type': 'application/json; charset=utf-8',
},
);
////print(response.body);
return categoryModelFromJson(response.body);
}on Exception catch (e){
print(e);
CategoryModel reply=CategoryModel();
return reply;
}
}
========
// To parse this JSON data, do
//
// final categoryModel = categoryModelFromJson(jsonString);
import 'dart:convert';
CategoryModel categoryModelFromJson(String str) => CategoryModel.fromJson(json.decode(str));
String categoryModelToJson(CategoryModel data) => json.encode(data.toJson());
class CategoryModel {
List<CategoryModelCategory> categories;
CategoryModel({
this.categories,
});
factory CategoryModel.fromJson(Map<String, dynamic> json) => CategoryModel(
categories: List<CategoryModelCategory>.from(json["categories"].map((x) => CategoryModelCategory.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"categories": List<dynamic>.from(categories.map((x) => x.toJson())),
};
}
class CategoryModelCategory {
int id;
String idParent;
String levelDepth;
String nbProductsRecursive;
String active;
String idShopDefault;
String isRootCategory;
String position;
String dateAdd;
String dateUpd;
String name;
String linkRewrite;
String description;
String metaTitle;
String metaDescription;
String metaKeywords;
Associations associations;
CategoryModelCategory({
this.id,
this.idParent,
this.levelDepth,
this.nbProductsRecursive,
this.active,
this.idShopDefault,
this.isRootCategory,
this.position,
this.dateAdd,
this.dateUpd,
this.name,
this.linkRewrite,
this.description,
this.metaTitle,
this.metaDescription,
this.metaKeywords,
this.associations,
});
factory CategoryModelCategory.fromJson(Map<String, dynamic> json) => CategoryModelCategory(
id: json["id"],
idParent: json["id_parent"],
levelDepth: json["level_depth"],
nbProductsRecursive: json["nb_products_recursive"],
active: json["active"],
idShopDefault: json["id_shop_default"],
isRootCategory: json["is_root_category"],
position: json["position"],
dateAdd: json["date_add"],
dateUpd: json["date_upd"],
name: json["name"],
linkRewrite: json["link_rewrite"],
description: json["description"],
metaTitle: json["meta_title"],
metaDescription: json["meta_description"],
metaKeywords: json["meta_keywords"],
associations: Associations.fromJson(json["associations"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"id_parent": idParent,
"level_depth": levelDepth,
"nb_products_recursive": nbProductsRecursive,
"active": active,
"id_shop_default": idShopDefault,
"is_root_category": isRootCategory,
"position": position,
"date_add": dateAdd,
"date_upd": dateUpd,
"name": name,
"link_rewrite": linkRewrite,
"description": description,
"meta_title": metaTitle,
"meta_description": metaDescription,
"meta_keywords": metaKeywords,
"associations": associations.toJson(),
};
}
class Associations {
List<ProductElement> categories;
List<ProductElement> products;
Associations({
this.categories,
this.products,
});
factory Associations.fromJson(Map<String, dynamic> json) => Associations(
categories: List<ProductElement>.from(json["categories"].map((x) => ProductElement.fromJson(x))),
products: List<ProductElement>.from(json["products"].map((x) => ProductElement.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"categories": List<dynamic>.from(categories.map((x) => x.toJson())),
"products": List<dynamic>.from(products.map((x) => x.toJson())),
};
}
class ProductElement {
String id;
ProductElement({
this.id,
});
factory ProductElement.fromJson(Map<String, dynamic> json) => ProductElement(
id: json["id"],
);
Map<String, dynamic> toJson() => {
"id": id,
};
}