如何在dart Parse Json中使用类作为数据类型

时间:2019-01-13 19:58:02

标签: dart flutter

我有一个称为FullTrip的Main类,该类具有称为路线的属性,而其他则包含两段数据
所以我创建了另一个名为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

终端出现错误

  

[SEVERE] 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.0秒

     

[INFO]缓存已完成依赖关系图... [INFO]缓存已完成   依赖图完成,耗时68ms

1 个答案:

答案 0 :(得分: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);
}

您还应该查看警告:[警告] lib / models / fulltrip.dart上的json_serializable:缺少“ part'fulltrip.g.dart';”

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

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