dart Flutter中未调用fromJSON方法

qvtsj1bj  于 2023-04-09  发布在  Flutter
关注(0)|答案(3)|浏览(147)

我尝试调用此方法,但TempReceivtModel.fromJSON未被调用。

Future<TempReceiptModel?> getTempReceipt({
  required UserModel? user,
}) async {
  TempReceiptModel? tempReceipt;
  try {
    // print(tempReceipt.)
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String? accessToken = prefs.getString('accesstoken');
    String? userID = user?.user_id;
    http.Response res = await http.get(
      Uri.parse("http://localhost:3000/getTempReceipt/$userID"),
      headers: {
        "Authorization": "Bearer $accessToken",
      },
    );
    if (res.statusCode == 200) {
      Map<String, dynamic> Receipt = jsonDecode(res.body);
      tempReceipt = TempReceiptModel.fromJson(Receipt);
    }
    return tempReceipt;
  } catch (err) {
    return tempReceipt;
  }
}

以下是TempReceivtModel的代码

class TempReceiptModel {
  final String userID;
  final double tempWeight;
  var receipt;
  final String UID;

  TempReceiptModel({
    required this.userID,
    required this.tempWeight,
    required this.receipt,
    required this.UID,
  });

  static TempReceiptModel fromJson(Map<String, dynamic> json) {
    if(json['receipt']!=null ) {
      ReceiptObject.fromJson(json['receipt']);
    }
    return TempReceiptModel(
      userID: json['userID'],
      tempWeight: json['tempWeight'] ?? 0.0,
      receipt: json['receipt'],
      UID: json['UID'],
    );
  }

fromJSON方法调用ReceivtObject.fromJSON方法。以下是ReceivtObject模型的代码:

class ReceiptObject {
  final double totalWeight;
  final DateTime date;
  final double netTotal;
  final double totalDiscount;
  final double? gst;
  final bool isDeleted;
  final List<ItemModel> items;

  ReceiptObject({
    required this.totalWeight,
    required this.date,
    required this.netTotal,
    required this.totalDiscount,
    required this.isDeleted,
    required this.items,
    this.gst,
  });

  static ReceiptObject fromJson(Map<String, dynamic> json) {
    return ReceiptObject(
      totalWeight: json['totalWeight'],
      date: DateTime.parse(json['date']),
      netTotal: json['netTotal'],
      totalDiscount: json['totalDiscount'],
      gst: json['gst'],
      isDeleted: json['isDeleted'],
      items: (json['items'] as List<dynamic>)
          .map((e) => ItemModel.fromJson(e))
          .toList(),
    );
  }

下面是itemModel和itemModel.fromJSON方法

class ItemModel {
 final String productID;
 final int productQuantity;
 final double grossTotal;
  bool isDeleted=false;

  ItemModel(
      {
        required this.productID,
        required this.grossTotal,
        required this.productQuantity,
        required this.isDeleted,

      });

  static ItemModel fromJson(Map<String, dynamic> json) {
    return ItemModel(
        productID :json["productID"],
        grossTotal: json["grossTotal"],
        productQuantity:json["productQuantity"],
        isDeleted:json["isDeleted"]

    );
  }

Map<String, dynamic> toJson() {
  final Map<String, dynamic> data = new Map<String, dynamic>();
  data['productID']=this.productID;
  data['productQuantity']=this.productQuantity;
  data['grossTotal']=this.grossTotal;
  data['isDeleted']=this.isDeleted;
  return data;
}

}

模型保存在后端,如下所示

const mongoose = require('mongoose');
const receiptSchema = require('./receipt_model');

var tempReceiptSchema = new mongoose.Schema({
    userID: {
        type: String,
        required: true,
        unique: true
    },
    tempWeight: {
        type: Number,
        default: 0
    },
    receipt: {
        totalWeight: {
            type: Number,
            default: 0,
            required: true
        },
        date: {
            type: Date,
            default: Date.now(),
            required: true
        },
        netTotal: {
            type: Number,
            default: 0,
            required: true
        },
        totalDiscount: {
            type: Number,
            default: 0,
            required: true
        },
        gst: {
            type: Number,
        },
        isDeleted: {
            type: Boolean,
            default: false
        },
        items: [{
            productID: {
                type: String,
                required: true
            },
            productQuantity: {
                type: Number,
                required: true
            },
            grossTotal: {
                type: Number,
                required: true
            },
            // for soft delete
            isDeleted: {
                type: Boolean,
                default: false
            }
        }]
    },
    UID: {
        type: String,
        required: true
    }
})

const receipt = mongoose.model('tempReceipt', tempReceiptSchema)
module.exports = receipt

我收到这个对象作为响应:

{
"tempreceipt": {
    "receipt": {
        "totalWeight": 0.30000000000000004,
        "date": "2023-04-07T17:50:44.898Z",
        "netTotal": 540,
        "totalDiscount": 0,
        "isDeleted": false,
        "items": [
            {
                "productID": "63b2d175525a0799637150bc",
                "productQuantity": 3,
                "grossTotal": 540,
                "isDeleted": false,
                "_id": "64305818becb25d9ae1a6801"
            }
        ]
    },
    "_id": "643057ffbecb25d9ae1a67f0",
    "userID": "641f4d6a11a2885a78550113",
    "tempWeight": 0,
    "UID": " D9 B9 B1 D5",
    "__v": 1
}

}
我希望从TempReceive.fromJSON方法返回TempReceivtModel。

hgqdbh6s

hgqdbh6s1#

亲爱的你调用的方法名不对,你在物料模型类中有这个方法(静态ItemModel fromJson),你调用的是类似这个方法TempReceivtModel.fromJson(Receipt),所以这个名字是错误的。

如何解决?
Ans:您可以转到此链接并自动创建您的模型类。

https://app.quicktype.io/
所以请尝试一下。如果有任何问题,我可以为您服务。谢谢。

uqzxnwby

uqzxnwby2#

编辑后,根据你的json输出,你的模型应该看起来像这样:

import 'package:meta/meta.dart';
import 'dart:convert';

TemprRceiptModel temprRceiptModelFromJson(String str) => TemprRceiptModel.fromJson(json.decode(str));

String temprRceiptModelToJson(TemprRceiptModel data) => json.encode(data.toJson());

class TemprRceiptModel {
    TemprRceiptModel({
        required this.tempreceipt,
    });

    final Tempreceipt tempreceipt;

    factory TemprRceiptModel.fromJson(Map<String, dynamic> json) => TemprRceiptModel(
        tempreceipt: Tempreceipt.fromJson(json["tempreceipt"]),
    );

    Map<String, dynamic> toJson() => {
        "tempreceipt": tempreceipt.toJson(),
    };
}

class Tempreceipt {
    Tempreceipt({
        required this.receipt,
        required this.id,
        required this.userId,
        required this.tempWeight,
        required this.uid,
        required this.v,
    });

    final Receipt receipt;
    final String id;
    final String userId;
    final int tempWeight;
    final String uid;
    final int v;

    factory Tempreceipt.fromJson(Map<String, dynamic> json) => Tempreceipt(
        receipt: Receipt.fromJson(json["receipt"]),
        id: json["_id"],
        userId: json["userID"],
        tempWeight: json["tempWeight"],
        uid: json["UID"],
        v: json["__v"],
    );

    Map<String, dynamic> toJson() => {
        "receipt": receipt.toJson(),
        "_id": id,
        "userID": userId,
        "tempWeight": tempWeight,
        "UID": uid,
        "__v": v,
    };
}

class Receipt {
    Receipt({
        required this.totalWeight,
        required this.date,
        required this.netTotal,
        required this.totalDiscount,
        required this.isDeleted,
        required this.items,
    });

    final double totalWeight;
    final DateTime date;
    final int netTotal;
    final int totalDiscount;
    final bool isDeleted;
    final List<Item> items;

    factory Receipt.fromJson(Map<String, dynamic> json) => Receipt(
        totalWeight: json["totalWeight"]?.toDouble(),
        date: DateTime.parse(json["date"]),
        netTotal: json["netTotal"],
        totalDiscount: json["totalDiscount"],
        isDeleted: json["isDeleted"],
        items: List<Item>.from(json["items"].map((x) => Item.fromJson(x))),
    );

    Map<String, dynamic> toJson() => {
        "totalWeight": totalWeight,
        "date": date.toIso8601String(),
        "netTotal": netTotal,
        "totalDiscount": totalDiscount,
        "isDeleted": isDeleted,
        "items": List<dynamic>.from(items.map((x) => x.toJson())),
    };
}

class Item {
    Item({
        required this.productId,
        required this.productQuantity,
        required this.grossTotal,
        required this.isDeleted,
        required this.id,
    });

    final String productId;
    final int productQuantity;
    final int grossTotal;
    final bool isDeleted;
    final String id;

    factory Item.fromJson(Map<String, dynamic> json) => Item(
        productId: json["productID"],
        productQuantity: json["productQuantity"],
        grossTotal: json["grossTotal"],
        isDeleted: json["isDeleted"],
        id: json["_id"],
    );

    Map<String, dynamic> toJson() => {
        "productID": productId,
        "productQuantity": productQuantity,
        "grossTotal": grossTotal,
        "isDeleted": isDeleted,
        "_id": id,
    };
}

您可以使用quicktype.io基于JSON对象生成此dart模型

ecbunoof

ecbunoof3#

我将TempReceivtModel fromJSON方法更改为:

return TempReceiptModel(
    receipt: ReceiptObject.fromJson(json['tempreceipt']['receipt']),
    userID: json['tempreceipt']['userID'],
    tempWeight: json['tempreceipt']['tempWeight'].toDouble(),
    uid: json['tempreceipt']['UID'],
    );

我没有修改代码的其余部分,它工作了。

相关问题