使用Json_Serializable

时间:2018-08-16 08:10:43

标签: json flutter

我试图在我的flutter应用程序中访问本地JSON文件,但是在如何进行操作上受阻: 1)将json文件加载到我的项目中 2)使用我组装在一起的序列化模块对其进行解析/解码。

序列化模块类的代码:

import 'package:json_annotation/json_annotation.dart';

part 'testJson.g.dart';

@JsonSerializable()
class BaseResponse extends Object with _$BaseResponseSerializerMixin {

  final List<Topics> topic;

  BaseResponse(
      this.topic
      );

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

@JsonSerializable()
class Topics extends Object with _$TopicsSerializerMixin {
  final int id;
  final String name;
  final String color;
  final List<Reading> reading;
  final int tCompletion;


  Topics(
    this.id,
      this.name,
      this.color,
      this.reading,
      this.tCompletion

);

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

@JsonSerializable()
class Reading extends Object with _$ReadingSerializerMixin{
  final String name;
  final int nLos;
  final String description;
  final String summary;
  final List<LOS> los;
  final int  rCompletion;

  Reading(
      this.name,
      this.nLos,
      this.description,
      this.summary,
      this.los,
      this.rCompletion,
      );

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

@JsonSerializable()
class LOS extends Object with _$LOSSerializerMixin{
  final int id;
  final String objective;
  final String description;
  final String formulae;

  LOS(this.id, this.objective, this.description, this.formulae);

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


@JsonLiteral('jsondata.json')
Map get glossaryData => _$glossaryDataJsonLiteral;

我已经建立了一个模型来解释主题类的响应

class topicModel {

  final String topic;
  final String color;
  final int completion;


  topicModel({
    this.topic,
    this.color,
    this.completion

  });

  topicModel.fromResponse(Topics response)
  : topic = response.name,
    color = response.color,
    completion = response.tCompletion;

}

我正在尝试使用将来的构建器来加载本地JSON文件,但是正在努力返回数据并通过类/模型进行解析

Widget build(BuildContext context) {
  return FutureBuilder(
      future: getData(context: context),
    builder: (BuildContext context, AsyncSnapshot<List> jsonData) {
        if (!jsonData.hasData) {
        return Text('not loaded');
        }
        return Text('loaded'); 

        },


}
      Future<List<topicModel>> getData({BuildContext context}) async {
  String data = await DefaultAssetBundle.of(context).loadString("assets/data/jsondata.json");
  Map jsonMap = json.decode(data);

  var testdata = BaseResponse.fromJson(jsonMap);
  return topicModel.fromResponse(testdata) as List;

}

0 个答案:

没有答案