Flutter JSON转Dart模型插件json2dart_db的使用

发布于 1周前 作者 gougou168 来自 Flutter

Flutter JSON转Dart模型插件json2dart_db的使用

json2dart_db 的数据库支持

  • 1.可根据model生成表结构。
  • 2.支持表升级。

一.模型以及表的生成

选择一个json模型,将模型复制到生成的插件中。

根据上方图片显示:

  • ClassName 只需要下划线的文件名(会自动生成文件跟对应的模型的驼峰式名字)
  • 勾选Sqlite Support,然后可以在右方的输入框中输入primaryKey(Ps:primary key如果是json中已有的,只会有PRIMARY KEY 的属性,如果是json数据中没有的,会根据输入的自动增加一个属性到model的模型类中,并带有PRIMARY KEYAUTOINCREMENT)
  • json 模型可以选择lib下的任何目录,生成的模型会在选择的文件夹下,dao类的生成只会生成在lib/database的目录下,并在有新表时,自动插入生成语句到代码的方法中

1.下面简单演示一下生成:取一段json,如下

{
  "name": "default",
  "playlist_count": "",
  "create_time": 0,
  "position": 1,
  "playlist_ids": [
    1
  ]
}

2.调用插件,生成的模型和dao类,分别如下

为了支持数据库以及更好的区分bean,会override以下三个方法:

  • hashCode== (equal) 方法
  • 自动with基类(BaseDbModel,不使用extends,方便给其它基类继承),实现primaryKeyAndValue
import 'dart:convert';

import 'package:json2dart_safe/json2dart.dart';

class CategoryDaoTest with BaseDbModel {
  String? playlistCount;
  List<int>? playlistIds;
  int? createTime;
  String? name;
  int? position;
  int? categoryId;

  CategoryDaoTest({
    this.playlistCount,
    this.playlistIds,
    this.createTime,
    this.name,
    this.position,
    this.categoryId,
  });

  [@override](/user/override)
  Map<String, dynamic> toJson() =>
      {
        'playlist_count': playlistCount,
        'playlist_ids': playlistIds,
        'create_time': createTime,
        'name': name,
        'position': position,
        'category_id': categoryId,
      };

  CategoryDaoTest.fromJson(Map json) {
    playlistCount = json.asString('playlist_count');
    playlistIds = json.asList<int>('playlist_ids');
    createTime = json.asInt('create_time');
    name = json.asString('name');
    position = json.asInt('position');
    categoryId = json.asInt('category_id');
  }

  static CategoryDaoTest toBean(Map json) => CategoryDaoTest.fromJson(json);

  [@override](/user/override)
  Map<String, dynamic> primaryKeyAndValue() => {"category_id": categoryId};

  [@override](/user/override)
  int get hashCode => categoryId?.hashCode ?? super.hashCode;

  [@override](/user/override)
  bool operator ==(Object other) {
    if (other is CategoryDaoTest && categoryId != null) {
      return other.categoryId == categoryId;
    }
    return super == other;
  }

  [@override](/user/override)
  String toString() => jsonEncode(toJson());
}

生成的dao类如下,目前可支持多表,但需要手动调用执行表生成的语句:

import 'package:json2dart_safe/json2dart.dart';
import 'package:gesound/common/model/category_dao_test.dart';

class CategoryDaoTestDao extends BaseDao<CategoryDaoTest> {
  static const String _tableName = 'category_dao_test';

  CategoryDaoTestDao() : super(_tableName, 'category_id');

  static String tableSql([String? tableName]) =>
      ""
      "CREATE TABLE IF NOT EXISTS `${tableName ?? _tableName}` ("
      "`playlist_count` TEXT,"
      "`playlist_ids` TEXT,"
      "`create_time` INTEGER,"
      "`name` TEXT,"
      "`position` INTEGER,"
      "`category_id` INTEGER PRIMARY KEY AUTOINCREMENT)";

  [@override](/user/override)
  CategoryDaoTest fromJson(Map json) => CategoryDaoTest.fromJson(json);
}

更多关于Flutter JSON转Dart模型插件json2dart_db的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter JSON转Dart模型插件json2dart_db的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是如何在Flutter项目中使用json2dart_db插件将JSON数据转换为Dart模型的详细步骤和代码示例。json2dart_db插件通常用于快速生成Dart模型类,从而简化JSON数据的解析过程。不过,需要注意的是,这个插件的具体功能和名称可能在不同时间有所变化,因此这里提供一个通用的步骤和假设的代码示例。

步骤 1: 添加依赖

首先,在你的pubspec.yaml文件中添加json2dart_db(或类似功能的插件)的依赖。由于json2dart_db可能不是一个实际存在的插件名称,这里我们使用一个类似的插件json_annotation作为替代,并展示如何使用它来生成模型。

dependencies:
  flutter:
    sdk: flutter
  json_annotation: ^4.3.0  # 使用json_annotation作为示例

然后运行flutter pub get来安装依赖。

步骤 2: 创建JSON数据

假设你有以下JSON数据需要转换为Dart模型:

{
  "name": "John Doe",
  "age": 30,
  "email": "johndoe@example.com"
}

步骤 3: 使用json_serializable生成Dart模型

虽然json2dart_db可能不是实际存在的插件,但json_serializable是Flutter社区广泛使用的用于JSON序列化和反序列化的插件。

  1. 添加构建依赖: 在pubspec.yaml中添加json_serializable的构建依赖。

    dev_dependencies:
      build_runner: ^2.1.4
      json_serializable: ^6.1.4
    
  2. 创建Dart模型: 创建一个Dart文件(例如user_model.dart),并定义你的模型类。使用[@JsonSerializable](/user/JsonSerializable)()注解来标记类,并使用fromJsontoJson方法来序列化和反序列化JSON数据。

    import 'package:json_annotation/json_annotation.dart';
    
    part 'user_model.g.dart';
    
    [@JsonSerializable](/user/JsonSerializable)()
    class UserModel {
      final String name;
      final int age;
      final String email;
    
      UserModel({required this.name, required this.age, required this.email});
    
      // 从JSON生成UserModel对象
      factory UserModel.fromJson(Map<String, dynamic> json) => _$UserModelFromJson(json);
    
      // 将UserModel对象转换为JSON
      Map<String, dynamic> toJson() => _$UserModelToJson(this);
    }
    
  3. 生成代码: 在终端中运行以下命令来生成user_model.g.dart文件,这个文件包含了fromJsontoJson方法的实现。

    flutter pub run build_runner build
    

步骤 4: 使用生成的模型

现在你可以在你的Flutter应用中使用这个模型来解析和生成JSON数据了。

import 'package:flutter/material.dart';
import 'user_model.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('JSON to Dart Model Example'),
        ),
        body: Center(
          child: UserInfoWidget(),
        ),
      ),
    );
  }
}

class UserInfoWidget extends StatelessWidget {
  final String jsonData = '''
  {
    "name": "John Doe",
    "age": 30,
    "email": "johndoe@example.com"
  }
  ''';

  @override
  Widget build(BuildContext context) {
    // 解析JSON数据
    final UserModel user = UserModel.fromJson(jsonDecode(jsonData));

    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Text('Name: ${user.name}'),
        Text('Age: ${user.age}'),
        Text('Email: ${user.email}'),
      ],
    );
  }
}

在这个示例中,我们展示了如何使用json_serializable插件来自动生成Dart模型类,并解析JSON数据。虽然json2dart_db可能不是实际存在的插件,但这个过程是处理JSON数据转换为Dart模型的通用方法。如果你的插件名称和功能有所不同,请查阅相关文档以获取具体的使用方法。

回到顶部