调用T类Tojson方法

发布于 2025-02-09 19:00:34 字数 743 浏览 1 评论 0原文

我是Dart&扑。我必须将数据发布到Internet。

我将使用通用类方法为此。 另一方面,我需要将我的对象转换为JSON。 但是,如何通过T级课程或还有其他优雅的方式呢?

你能给我一个意见吗?

Future<ReturnModel> postData<T>(T model) async {
  final response = await http.post(
      Uri.parse('https://localhost/SomeAddress'),
      headers: <String, String>{
        'Content-Type': 'application/json; charset=UTF-8',
      },

      //**
      IDE gives error here of course. 
      Because it is not know type of T.
      How can i get over this?
      **//
      body: jsonEncode(model.toJson())
  );

  if (response.statusCode == StatusCode.OK) {
    return ReturnModel.fromJson(jsonDecode(response.body));
  } else {
    throw Exception('Bir hata oluştu.');
  }
}

I'm new on Dart & Flutter. I have to post data to internet.

I would to use a common class method for this.
In other hand i need to convert my object to JSON.
But how can do it with T class or is there other elegant way?

Could you give me an opinion?

Future<ReturnModel> postData<T>(T model) async {
  final response = await http.post(
      Uri.parse('https://localhost/SomeAddress'),
      headers: <String, String>{
        'Content-Type': 'application/json; charset=UTF-8',
      },

      //**
      IDE gives error here of course. 
      Because it is not know type of T.
      How can i get over this?
      **//
      body: jsonEncode(model.toJson())
  );

  if (response.statusCode == StatusCode.OK) {
    return ReturnModel.fromJson(jsonDecode(response.body));
  } else {
    throw Exception('Bir hata oluştu.');
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

冰雪之触 2025-02-16 19:00:34
body: jsonEncode(((model) as dynamic).toJson())
body: jsonEncode(((model) as dynamic).toJson())
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文