【问题标题】:How to encode Object to Json in flutter如何在颤动中将对象编码为 Json
【发布时间】:2021-04-20 08:54:54
【问题描述】:

我有一个主题对象

class Subject {
  String subjectName;
  int pages;
  int fullMarks;

  Future<Map<String, dynamic>> toJson() async {
    return {
      'name': name,
      'pages': pages,
      'fullMarks': fullMarks,
    }
  }
}

和学生对象

class Student {
  String name;
  int rank;
  Subject sub;

  Future<Map<String, dynamic>> toJson() async {
    return {
      'name': name,
      'rank': rank,
      'subject': sub.toJson(),
    }
  }
}

我想在 POST 请求中发送这个学生对象。

我做到了:这里的 student 是 Student 类的对象。

var data = jsonEncode(await student.toJson());

但在数据中主题值为空。 有谁知道为什么??

【问题讨论】:

  • 您是否尝试过调试代码并检查student.sub 是否为非空?
  • 是的,主题对象不为空,我已调试。

标签: android json flutter serialization http-post


【解决方案1】:

您需要在sub.toJson()之前添加await作为

'subject': await sub.toJson()

await 将允许future 在等待结果的同时完成,否则将立即返回future 对象,这是不希望的。

【讨论】:

  • 甚至更好,不要让toJson()函数async,没必要
  • @mfkw1 感谢这也有效,我是 dart 和 flutter 的新手,所以对 async 和 await 有点困惑。
猜你喜欢
  • 1970-01-01
  • 2020-08-11
  • 2019-10-17
  • 2012-06-10
  • 2020-05-23
  • 2023-04-02
  • 2021-04-21
  • 1970-01-01
  • 2020-07-23
相关资源
最近更新 更多