繁体   English   中英

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

[英]how to Use class as datatype in dart Parse Json

我有一个称为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时出错,由于类型为Hc无法从fromJson代码生成itineraries 提供的TypeHelper实例TypeHelper支持定义的类型。 package:Tourism / models / fulltrip.dart:21:18 final列出行程; ^^^^^^^^^^^^^ [警告] lib / models / fulltrip.dart上的json_serializable:缺少“ part'fulltrip.g.dart';”。 [INFO]运行版本完成,花了3.0秒

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

问题似乎是您必须将两个类拆分为单独的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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM