我有这个API调用,在给定搜索食物名称的情况下,我向Nutritionix(API提供者)询问食物数据。我已经完成了JSON反序列化,但是我不得不序列化响应的某些部分(不是全部),以便可以将其放入数据库中,但是当我尝试对Firebase数据进行反序列化时,我的用户可以在应用程序中使用它。 (用例是当用户强制退出应用程序时,所有本地存储的变量都将被清除,因此在启动应用程序时,我检查数据库中是否已存在用户已记录早餐/午餐/晚餐食物的记录今天,因此仅在db中显示保存的食物日志)
这是响应的样子:
{
"foods": [
{
"food_name": "cheeseburger","brand_name": null,"serving_qty": 1,"serving_unit": "item","serving_weight_grams": 199,"nf_calories": 535.31,"nf_total_fat": 28.66,"nf_saturated_fat": 14,"nf_cholesterol": 95.52,"nf_sodium": 1176.09,"nf_total_carbohydrate": 39.24,"nf_dietary_fiber": 2.39,"nf_sugars": 7.16,"nf_protein": 30.27,"nf_potassium": 443.77,"nf_p": 364.17,"full_nutrients": [
{
"attr_id": 203,"value": 30.2679
},{
"attr_id": 204,"value": 28.656
},{
"attr_id": 205,"value": 39.2428
},{
"attr_id": 207,"value": 4.5969
},{
"attr_id": 208,"value": 535.31
},{
"attr_id": 209,"value": 25.87
},{
"attr_id": 210,"value": 0.2985
},{
"attr_id": 211,"value": 1.8507
},{
"attr_id": 212,"value": 2.5671
},{
"attr_id": 213,"value": 0.9353
},{
"attr_id": 214,"value": 1.5124
},{
"attr_id": 221,"value": 0
},{
"attr_id": 255,"value": 96.2364
},{
"attr_id": 262,{
"attr_id": 263,{
"attr_id": 268,"value": 2242.73
},{
"attr_id": 269,"value": 7.164
},{
"attr_id": 291,"value": 2.388
},{
"attr_id": 301,"value": 356.21
},{
"attr_id": 303,"value": 2.0298
},{
"attr_id": 304,"value": 51.74
},{
"attr_id": 305,"value": 364.17
},{
"attr_id": 306,"value": 443.77
},{
"attr_id": 307,"value": 1176.09
},{
"attr_id": 309,"value": 5.6317
},{
"attr_id": 312,"value": 0.1493
},{
"attr_id": 315,"value": 0.3244
},{
"attr_id": 317,"value": 49.153
},{
"attr_id": 318,"value": 471.63
},{
"attr_id": 319,"value": 93.53
},{
"attr_id": 320,"value": 101.49
},{
"attr_id": 321,{
"attr_id": 322,"value": 1.99
},{
"attr_id": 323,"value": 0.398
},{
"attr_id": 324,"value": 5.97
},{
"attr_id": 328,"value": 0.199
},{
"attr_id": 334,"value": 3.98
},{
"attr_id": 337,"value": 1611.9
},{
"attr_id": 338,"value": 33.83
},{
"attr_id": 341,"value": 5.4924
},{
"attr_id": 342,"value": 0.6368
},{
"attr_id": 343,"value": 0.1194
},{
"attr_id": 345,{
"attr_id": 346,{
"attr_id": 347,{
"attr_id": 401,"value": 0.597
},{
"attr_id": 404,"value": 0.2368
},{
"attr_id": 405,"value": 0.5174
},{
"attr_id": 406,"value": 8.0595
},{
"attr_id": 410,"value": 1.1741
},{
"attr_id": 415,"value": 0.1851
},{
"attr_id": 417,"value": 31.84
},{
"attr_id": 418,"value": 3.4825
},{
"attr_id": 421,"value": 75.023
},{
"attr_id": 429,{
"attr_id": 430,"value": 8.756
},{
"attr_id": 431,"value": 23.88
},{
"attr_id": 432,"value": 7.96
},{
"attr_id": 435,"value": 47.76
},{
"attr_id": 601,"value": 95.52
},{
"attr_id": 606,"value": 13.9957
},{
"attr_id": 607,"value": 0.3861
},{
"attr_id": 608,"value": 0.1313
},{
"attr_id": 609,"value": 0.0975
},{
"attr_id": 610,"value": 0.2149
},{
"attr_id": 611,"value": 0.2527
},{
"attr_id": 612,"value": 1.4428
},{
"attr_id": 613,"value": 7.2177
},{
"attr_id": 614,"value": 3.7651
},{
"attr_id": 615,"value": 0.0398
},{
"attr_id": 617,"value": 10.6306
},{
"attr_id": 618,"value": 2.0079
},{
"attr_id": 619,{
"attr_id": 620,"value": 0.0577
},{
"attr_id": 621,{
"attr_id": 624,{
"attr_id": 625,{
"attr_id": 626,"value": 0.9174
},{
"attr_id": 627,"value": 0.1552
},{
"attr_id": 628,{
"attr_id": 629,{
"attr_id": 630,{
"attr_id": 631,{
"attr_id": 645,"value": 11.8584
},{
"attr_id": 646,"value": 2.5154
},{
"attr_id": 652,"value": 0.1751
},{
"attr_id": 653,"value": 0.2726
},{
"attr_id": 654,{
"attr_id": 672,{
"attr_id": 687,{
"attr_id": 689,{
"attr_id": 697,"value": 0
}
],"nix_brand_name": null,"nix_brand_id": null,"nix_item_name": null,"nix_item_id": null,"upc": null,"consumed_at": "2019-11-12T10:40:37+00:00","metadata": {
"is_raw_food": false
},"source": 1,"ndb_no": 21398,"tags": {
"item": "cheeseburger","measure": null,"quantity": "1.0","food_group": 8,"tag_id": 445
},"alt_measures": [
{
"serving_weight": 199,"measure": "item","seq": 1,"qty": 1
},{
"serving_weight": 100,"measure": "g","seq": null,"qty": 100
},{
"serving_weight": 28.3495,"measure": "wt. oz","qty": 1
}
],"lat": null,"lng": null,"meal_type": 1,"photo": {
"thumb": "https://d2xdmhkmkbyw75.cloudfront.net/445_thumb.jpg","highres": "https://d2xdmhkmkbyw75.cloudfront.net/445_highres.jpg","is_user_uploaded": false
},"sub_recipe": null
}
]
}
这是我的反序列化模型和序列化模型,因此可以将其放在我的cloud_firestore数据库中:
class Nutritionix {
List<Food> food;
Nutritionix({this.food});
factory Nutritionix.fromJson(Map<String,dynamic> parsedJson) {
var list = parsedJson['foods'] as List;
List<Food> foodList = list.map((i) => Food.fromJson(i)).toList();
return Nutritionix(food: foodList);
}
}
class Food {
String foodName;
double servingQuantity;
double serving_weight;
double calories;
double totalFat;
double saturatedFat;
double cholesterol;
double sodium;
double totalCarbohydrate;
double dietaryFiber;
double sugar;
double protein;
double potassium;
double phospate;
List<Nutrients> nutrients;
Photo photo;
Food(
{this.foodName,this.servingQuantity,this.serving_weight,this.calories,this.totalFat,this.saturatedFat,this.cholesterol,this.sodium,this.totalCarbohydrate,this.dietaryFiber,this.sugar,this.protein,this.potassium,this.phospate,this.nutrients,this.photo});
factory Food.fromJson(Map<String,dynamic> parsedJson) {
var list = parsedJson['full_nutrients'] as List;
List<Nutrients> nutrientsList =
list.map((i) => Nutrients.fromJson(i)).toList();
//TODO: FIX ALL IF NULL AND ADD OTHER SERVING SIZES
return Food(
foodName: parsedJson['food_name'],servingQuantity: parsedJson['serving_qty'].toDouble(),serving_weight: parsedJson['serving_weight_grams'] != null
? parsedJson['serving_weight_grams'].toDouble()
: 0,calories: parsedJson['nf_calories'] != null
? parsedJson['nf_calories'].toDouble()
: 0,totalFat: parsedJson['nf_total_fat'] != null
? parsedJson['nf_total_fat'].toDouble()
: 0,saturatedFat: parsedJson['nf_saturated_fat'] != null
? parsedJson['nf_saturated_fat'].toDouble()
: 0,cholesterol: parsedJson['nf_cholesterol'] != null
? parsedJson['nf_cholesterol'].toDouble()
: 0,sodium: parsedJson['nf_sodium'] != null
? parsedJson['nf_sodium'].toDouble()
: 0,totalCarbohydrate: parsedJson['nf_total_carbohydrate'] != null
? parsedJson['nf_total_carbohydrate'].toDouble()
: 0,dietaryFiber: parsedJson['nf_dietary_fiber'] != null
? parsedJson['nf_dietary_fiber'].toDouble()
: 0,sugar: parsedJson['nf_sugars'] != null
? parsedJson['nf_sugars'].toDouble()
: 0,protein: parsedJson['nf_protein'] != null
? parsedJson['nf_protein'].toDouble()
: 0,potassium: parsedJson['nf_protein'] != null
? parsedJson['nf_potassium'].toDouble()
: 0,phospate:
parsedJson['nf_p'] != null ? parsedJson['nf_p'].toDouble() : 0,nutrients: nutrientsList,photo: Photo.fromJson(parsedJson['photo']));
}
//JSON SERIALIZATION SO I CAN INPUT IT IN MY DB
Map<String,dynamic> toJson() {
return {
"foodName": foodName,"servingQuantity": servingQuantity,"serving_weight": serving_weight,"calories": calories,"totalFat": totalFat,"saturatedFat": saturatedFat,"cholesterol": cholesterol,"sodium": sodium,"totalCarbohydrate": totalCarbohydrate,"dietaryFiber": dietaryFiber,"sugar": sugar,"protein": protein,"potassium": potassium,"phospate": phospate,"photo": photo.toJson()
};
}
}
class Nutrients {
int attributeID;
double value;
Nutrients({this.attributeID,this.value});
factory Nutrients.fromJson(Map<String,dynamic> parsedJson) {
return Nutrients(
attributeID: parsedJson['attr_id'],value: parsedJson['value'].toDouble());
}
}
class Photo {
String thumbnail;
String highRes;
Photo({this.highRes,this.thumbnail});
factory Photo.fromJson(Map<String,dynamic> parsedJson) {
return Photo(
highRes: parsedJson['thumbnail'],thumbnail: parsedJson['thumb']);
}
Map<String,dynamic> toJson(){
return{
"highRes": highRes,"thumbnail": thumbnail
};
}
}
这是我获取文档的代码:
void checkMealsList() async {
final mUserData = Provider.of<UserData>(context);
final userLoggedin = mUserData.mUData;
int index = userLoggedin.length - 1;
List<MealsListData> mealEntry = MealsListData.mealEntry;
print('im inside the checkmealslistfunc');
var breakfastDocument = await Firestore.instance
.collection('users')
.document(mUser.uid)
.collection('food')
.document(DateFormat.yMMMd().format(today))
.collection('Breakfast');
breakfastDocument.getDocuments().then((Querysnapshot query) {
query.documents.forEach((f) {
print(f.data);
//EDITING THE INDEX OF A LIST GIVEN A CONDITION
var newEntry = mealEntry.firstWhere((id) => id.id == f.data['id'],orElse: null);
if (newEntry!= null){
newEntry.meals = f.data['meals'];
print(newEntry.meals);
newEntry.mealType = f.data['mealType'];
print(newEntry.mealType);
newEntry.nutritionix = Nutritionix.fromJson(f.data['nutritionixData']);
// print('this is ${newEntry.nutritionix.food[0].protein}');
}
});
});//.catchError((onError) => onError);
}
我得到的错误是:
E/flutter ( 8204): #3 _rootRunUnary (dart:async/zone.dart:1132:38)
E/flutter ( 8204): #4 _CustomZone.runUnary (dart:async/zone.dart:1029:19)
E/flutter ( 8204): #5 _FutureListener.handleValue (dart:async/future_impl.dart:137:18)
E/flutter ( 8204): #6 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:678:45)
E/flutter ( 8204): #7 Future._propagateToListeners (dart:async/future_impl.dart:707:32)
E/flutter ( 8204): #8 Future._completeWithValue (dart:async/future_impl.dart:522:5)
E/flutter ( 8204): #9 _AsyncAwaitCompleter.complete (dart:async-patch/async_patch.dart:30:15)
E/flutter ( 8204): #10 _completeonAsyncReturn (dart:async-patch/async_patch.dart:288:13)
E/flutter ( 8204): #11 Query.getDocuments (package:cloud_firestore/src/query.dart)
E/flutter ( 8204): <asynchronous suspension>
E/flutter ( 8204): #12 _fitnessAppHomeScreenState.checkMealsList
我的序列化方法有问题吗?还是应该对Firebase记录进行单独的反序列化?任何帮助,将不胜感激! :)