flutter中的json转对象

本文介绍了一种在Flutter中将JSON数据转换为实体类的方法,避免了使用在线工具和插件带来的不便。通过解析JSON内容并自动生成实体类代码,提高了开发效率。

网上有好多json转对象的方法:
在线生成的:https://javiercbk.github.io/json_to_dart/
弊端:每次都要打开网页去生成,尤其是公司网不好的时候,急死;

插件生成的:插件名:FlutterJsonBeanFactory
弊端:不知道没弄明白还是根本没法设置,我只想要一个简单的文件,不要什么继承.
因为子类型总是重复生成.

以下我自己解析json内容生成对象[优化后]

只涉及到自己用到的类型,如有其他,读者可随时更改

import 'dart:convert';
import 'dart:io';

import 'package:flutter_test/flutter_test.dart';

void main() {
   test('生成实体数据', () async {
    Future<void> write(String fileName, String content) async {
      File indexFile = File(fileName);
      if (!await indexFile.exists()) {
        indexFile.createSync();
      } else {
        print("重写:$indexFile");
      }
      IOSink out = indexFile.openWrite();
      out.write(content);
    }

    String jsonFile = "models.json"; // json文件
    String jsonData = await File(jsonFile).readAsString();
    Map<String, dynamic> entities = convert.json.decode(jsonData);

    String filePath = entities.remove('path') ?? "lib/model"; // 生成目录,不带/后缀
    String libraryName = entities.remove('library') ?? "xgcs_model"; // 模块名称
    String entitySuffix = entities.remove('suffix') ?? "Entity"; // 实体后缀

    File libraryFile = File("$filePath/index.dart");
    await libraryFile.parent.create();

    Map<String, String> keyClassNameMap = {};
    for (String fileName in entities.keys) {
      Map<String, dynamic> data = entities[fileName];

      String className = fileName.substring(0, 1).toUpperCase() + fileName.substrin
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值