【问题标题】:I want to convert JSON data to a generic type in Flutter我想在 Flutter 中将 JSON 数据转换为泛型类型
【发布时间】:2021-04-06 18:05:04
【问题描述】:

大家好,我是 Flutter 的新手。 我想在 Flutter 中将 JSON 数据转换为泛型。

class ServiceResult<T>
{
  T result;
  String message;
  bool hasError;
  bool hasSuccessMessage;
}

我可以使用 地图 但我不想动态使用它。我想投给T。 我一直在我的研究中看到动态用途。有没有可以直接转换为 T 的方法?

【问题讨论】:

    标签: json flutter dart generics


    【解决方案1】:

    你无法避免使用 Map。 因为这是将 JSON 映射到类对象的唯一方法,但如果您更喜欢将 JSON 转换为 T 类,这里是示例。 首先,像你一样创建 ServiceResult 然后为结果创建 T 类

    class ServiceResult
    {
      T result;
      String message;
      bool hasError;
      bool hasSuccessMessage;
    }
    class T{
      String yourStringHere;
      String yourAnotherStringHere;
      int yourIntHere;
    }
    

    关键部分

    ServiceResult.fromJson(Map<String, dynamic> json) {
        message= json['message'];
        hasError= json['has_error'];
        hasSuccessMessage= json['has_success_message'];
        result = json['result'] != null ? new result .fromJson(json['result']) : null;
    }
    T.fromJson(Map<String, dynamic> json) {
        yourStringHere= json['your_string_here'];
        yourAnotherStringHere= json['your_another_string_here'];
        yourIntHere= json['your_int_here'];
    }
    

    奖励:Javier Lecuona 创建了将 JSON 转换为类对象的天才工具,因此您可以像我一样偷懒:P 这里:https://javiercbk.github.io/json_to_dart/

    【讨论】:

    • 感谢您的回答,但这对我不起作用。因为T对我来说可以是任何东西。示例:UserDto,定义了这个类。结果 = json['result'] as T 不起作用。我得到这个错误。类型“_InternalLinkedHashMap”不是类型转换中“UserDto”类型的子类型
    • 在这种情况下,如果传入的类在列表中,我如何访问 fromJson?还是字典?
    • 欢迎您!哦,哇,现在我真的明白你的问题了。我认为您可以添加一个更高级的 JSON 解析器类来做到这一点,但我不推荐它。为什么 Rest API 会返回不一致的内容?
    • 其实我知道会出现哪些类型,但我仍然希望能够负担得起它们。我很惊讶这在 Dart 语言中如此困难-.-"
    • 确实,flutter 有时过于严格。但是,如果您担心自己的安全,我认为这是一个很好的观点:D,我希望其他人会为您的目标指明方向。但对我来说,我建议您对所有事情都过于严格 :D 并使您的 API 更加一致,这样您就不必担心意外错误。
    猜你喜欢
    • 2021-12-01
    • 2015-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-21
    • 1970-01-01
    相关资源
    最近更新 更多