【问题标题】:how to Use class as datatype in dart Parse Json如何在 dart Parse Json 中使用类作为数据类型
【发布时间】:2019-06-07 22:03:09
【问题描述】:

我有一个名为 FullTrip 的 Main 类,这个类具有称为 itineraries 的属性,其他包含两条数据
所以我创建了另一个名为 Hc 的类,现在我需要使用这种组合来解析来自服务器的 json 响应

class FullTrip extends Trip{

  final List<String> including;
  final List<String> excluding;
  final List<Hc> itineraries;
  final List<Hc> policies;

  FullTrip(this.including,this.excluding,this.itineraries,this.policies,int id,String title,double price,String overview,String hero_image): 
  super(id:id,title:title,price:price,overview:overview,hero_image:hero_image);


    factory FullTrip.fromJson(Map<String, dynamic> json) => 
        _$FullTripFromJson(json);
}

  class Hc {
    final String head;
    final String content;
    Hc({this.head,this.content});
  }

当我使用这样的代码并运行序列化命令时

flutter packages pub run build_runner build --delete-conflicting-outputs

终端出错

[严重] lib/models/fulltrip.dart 上的 json_serializable:运行时出错 JsonSerializableGenerator 无法生成fromJson 代码 itineraries 因为类型 Hc。没有提供TypeHelper 实例支持定义的类型。 package:Tourism/models/fulltrip.dart:21:18 最终名单 行程; ^^^^^^^^^^^ [警告] lib/models/fulltrip.dart 上的 json_serializable:缺少“part 'fulltrip.g.dart';”。 [信息] 运行构建完成,耗时 3.0s

[INFO] 缓存最终确定的依赖图... [INFO] 缓存最终确定 依赖图完成,耗时 68ms

【问题讨论】:

    标签: dart flutter


    【解决方案1】:

    问题似乎是您必须将两个类拆分为单独的 dart 文件。以下是两个 dart 文件的内容:

    FullTrip.dart

    import 'package:json_annotation/json_annotation.dart';
    
    part 'fulltrip.g.dart';
    
    @JsonSerializable()
    class FullTrip extends Trip{
    
      final List<String> including;
      final List<String> excluding;
      final List<Hc> itineraries;
      final List<Hc> policies;
    
      FullTrip(this.including,this.excluding,this.itineraries,this.policies,int id,String title,double price,String overview,String hero_image): 
      super(id:id,title:title,price:price,overview:overview,hero_image:hero_image);
    
    
      factory FullTrip.fromJson(Map<String, dynamic> json) => 
            _$FullTripFromJson(json);
    
      Map<String, dynamic> toJson() => _$FullTripToJson(this);
    }
    

    Hc.dart

    import 'package:json_annotation/json_annotation.dart';
    
    part 'hc.g.dart';
    
    @JsonSerializable()
    class Hc {
      final String head;
      final String content;
      Hc({this.head,this.content});
    
      factory Hc.fromJson(Map<String, dynamic> json) => _$HcFromJson(json);
    
      Map<String, dynamic> toJson() => _$HcToJson(this);
    }
    

    您还应该查看警告:[WARNING] json_serializable on lib/models/fulltrip.dart: Missing "part 'fulltrip.g.dart';"

    你总是必须在类的顶部添加“part”文件。

    查看官方文档以了解其外观:https://flutter.io/docs/development/data-and-backend/json#creating-model-classes-the-json_serializable-way

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-14
      • 1970-01-01
      相关资源
      最近更新 更多