:::

6-10-1 json 序列化

pubspec.yaml

dependencies:
  json_serializable: 3.5.1

dev_dependencies:
  build_runner: any

assets\json\data.json

{
    "data": [
        {
            "cate": "水果類",
            "img": "fruits",
            "info": [
                {
                    "id": "D0100101",
                    "kind": "水果類",
                    "title": "山竹",
                    "description": "生鮮,去皮及子,混合均勻打碎",
                    "heat": "66.7733",
                    "potassium": "81.7065",
                    "phosphorus": "12.4949"
                },
                {
                    "id": "D4300101",
                    "kind": "水果類",
                    "title": "蛋黃果",
                    "description": "生鮮,長形種,去皮及子,混合均勻打碎",
                    "heat": "95.8583",
                    "potassium": "288.7133",
                    "phosphorus": "20.076"
                }
            ]
        },
        {
            "cate": "豆類",
            "img": "beans",
            "info": [
                {
                    "id": "H01051",
                    "kind": "豆類",
                    "title": "白鳳豆平均值",
                    "description": "生,混合均勻磨碎",
                    "heat": "295.9715",
                    "potassium": "1272.5116",
                    "phosphorus": "399.7434"
                },
                {
                    "id": "H1505101",
                    "kind": "豆類",
                    "title": "紅扁豆仁",
                    "description": "生,乾貸,混合均勻磨碎",
                    "heat": "307.8857",
                    "potassium": "827.96",
                    "phosphorus": "270.488"
                }
            ]
        },
    ]
}

model\data_model\food_cate.dart

import 'package:json_annotation/json_annotation.dart';

part 'food_cate.g.dart';

@JsonSerializable()
class FoodCate {
  String cate;
  String img;
  List<FoodInfo> info;

  FoodCate({this.cate, this.info});

  Map<String, dynamic> toJson() => _$FoodCateToJson(this);

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

@JsonSerializable()
class FoodInfo {
  String id;
  String kind;
  String title;
  String description;
  String heat;
  String potassium;
  String phosphorus;

  FoodInfo({
    this.id,
    this.kind,
    this.title,
    this.description,
    this.heat,
    this.potassium,
    this.phosphorus,
  });

  Map<String, dynamic> toJson() => _$FoodInfoToJson(this);

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

在終端機執行:

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

 


:::

書籍目錄

展開 | 闔起

快速登入


http%3A%2F%2Fcampus-xoops.tn.edu.tw%2Fmodules%2Ftad_book3%2Fpage.php%3Ftbdsn%3D1900%26tbsn%3D42

計數器

今天: 724724724
昨天: 3068306830683068
總計: 8077229807722980772298077229807722980772298077229