Skip to content
| Marketplace
Sign in
Visual Studio Code>Other>FlutterJsonBeanFactoryX (VS Code)New to Visual Studio Code? Get it now.
FlutterJsonBeanFactoryX (VS Code)

FlutterJsonBeanFactoryX (VS Code)

treexi

|
3 installs
| (0) | Free
基于 FlutterJsonBeanFactoryX 的 VS Code 版本:从 JSON 生成 Dart Bean,并按 pubspec.yaml 中的 flutter_json 配置导包。
Installation
Launch VS Code Quick Open (Ctrl+P), paste the following command, and press enter.
Copied to clipboard
More Info

FlutterJsonBeanFactoryX (VS Code) 使用文档

English Version | 中文版

📋 目录

  • 功能特性
  • 安装方法
  • 快速开始
  • 核心功能
    • 1. JSON 转 Dart Bean
    • 2. 生成 Helper 文件
    • 3. 生成 json_field.dart
  • 配置说明
    • VS Code 设置
    • 项目配置 (pubspec.yaml)
  • 快捷键
  • 使用示例
  • 项目结构
  • 常见问题
  • 更新日志

✨ 功能特性

FlutterJsonBeanFactoryX 是一个强大的 VS Code 扩展,帮助 Flutter 开发者快速从 JSON 生成类型安全的 Dart 实体类。

主要特性

  • 🚀 一键生成:从 JSON 字符串快速生成 Dart Bean 类
  • 🎯 类型安全:支持泛型、嵌套对象、List、Map 等复杂类型
  • ⚡ 智能转换:自动将 JSON key 转换为驼峰命名法
  • 🛠️ 灵活配置:支持自定义生成路径、类名后缀等
  • 🔧 Helper 生成:自动生成 fromJson/toJson 辅助方法
  • 📦 模块化支持:支持多模块项目配置

📦 安装方法

方式一:从 VSIX 安装(推荐)

  1. 在扩展侧边栏点击 "..." 菜单
  2. 选择 "从 VSIX 安装..."
  3. 选择 vscode-extension/flutter-json-bean-factory-x-vscode-0.0.1.vsix
  4. 重启 VS Code

方式二:从源码构建

cd vscode-extension
npm install
npm run build

然后在 VS Code 中:

  1. 按 F5 启动调试(会打开一个新 VS Code 窗口)
  2. 或运行 vsce package 打包成 VSIX 文件

🚀 快速开始

第一步:配置项目

在你的 Flutter 项目的 pubspec.yaml 中添加配置:

# 示例配置
flutter_json:
  generated_path: lib/generated/json/  # 生成的文件存放路径
  module_path: module_a                # 模块路径(多模块项目使用)

第二步:安装依赖

确保你的项目已添加以下依赖:

dependencies:
  json_annotation: ^4.8.1

dev_dependencies:
  json_serializable: ^6.7.1
  build_runner: ^2.4.6

然后运行:

flutter pub get

第三步:生成你的第一个 Bean

  1. 在编辑器中打开任意 Dart 文件
  2. 选中一段 JSON 文本(或复制到剪贴板)
  3. 按 Alt+J (Windows/Linux) 或 ⌥+J (Mac)
  4. 输入类名(例如 UserEntity)
  5. 见证魔法!🎉

🎯 核心功能

1. JSON 转 Dart Bean

将 JSON 字符串转换为带有 @JsonSerializable() 注解的 Dart 类。

使用方法

方法 A:通过选中文本

  1. 在编辑器中选中 JSON 内容
  2. 按 Alt+J
  3. 输入类名
  4. 生成的文件将保存到配置的目录

方法 B:通过输入框

  1. 按 Alt+J(不选中任何文本)
  2. 在弹出的输入框中粘贴 JSON
  3. 输入类名
  4. 生成完成

方法 C:通过命令面板

  1. 按 Ctrl+Shift+P (Windows/Linux) 或 ⌘+Shift+P (Mac)
  2. 输入 "Flutter JSON → Dart Bean"
  3. 按提示操作

示例

输入 JSON:

{
  "code": 200,
  "message": "success",
  "data": {
    "user_id": "12345",
    "user_name": "张三",
    "email": "zhangsan@example.com",
    "is_vip": true,
    "balance": 99.99
  }
}

生成的 Dart 类:

import 'package:json_annotation/json_annotation.dart';

part 'user_response_entity.g.dart';

@JsonSerializable()
class UserResponseEntity {
  int? code;
  String? message;
  UserResponseData? data;

  UserResponseEntity();

  factory UserResponseEntity.fromJson(Map<String, dynamic> json) => _$UserResponseEntityFromJson(json);

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

@JsonSerializable()
class UserResponseData {
  @JSONField(name: "user_id")
  String? userId;
  
  @JSONField(name: "user_name")
  String? userName;
  
  String? email;
  
  @JSONField(name: "is_vip")
  bool? isVip;
  
  double? balance;

  UserResponseData();

  factory UserResponseData.fromJson(Map<String, dynamic> json) => _$UserResponseDataFromJson(json);

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

2. 生成 Helper 文件

为当前文件中所有 @JsonSerializable() 类生成 .g.dart 辅助文件。

使用方法

  1. 打开包含 @JsonSerializable() 类的 Dart 文件
  2. 按 Alt+H
  3. 扩展会自动识别所有需要生成辅助方法的类
  4. 在配置的目录下生成 .g.dart 文件

生成内容示例

对于上面的 UserResponseEntity 类,会生成:

// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'user_response_entity.dart';

// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************

UserResponseEntity _$UserResponseEntityFromJson(Map<String, dynamic> json) {
  return UserResponseEntity()
    ..code = jsonConvert.asT<int>(json['code'])
    ..message = jsonConvert.asT<String>(json['message'])
    ..data = jsonConvert.asT<UserResponseData>(json['data']);
}

Map<String, dynamic> _$UserResponseEntityToJson(UserResponseEntity instance) {
  return <String, dynamic>{
    'code': instance.code,
    'message': instance.message,
    'data': instance.data,
  };
}
// ... 其他类的生成方法

3. 生成 json_field.dart

生成基础的 JSON 字段注解文件,通常只需要执行一次。

使用方法

  1. 按 Ctrl+Shift+P
  2. 输入 "Generate json_field.dart"
  3. 选择命令执行
  4. 文件将生成在 generated_path/base/ 目录下

生成的文件:

// lib/generated/json/base/json_field.dart

class JSONField {
  final String? name;
  final bool? serialize;
  final bool? deserialize;

  const JSONField({this.name, this.serialize, this.deserialize});
}

⚙️ 配置说明

VS Code 设置

在 VS Code 设置中搜索 "FlutterJsonBeanFactoryX" 进行配置:

配置项 类型 默认值 说明
flutterJsonBeanFactory.modelSuffix string "entity" 生成的类名后缀,如 UserEntity 的 entity
flutterJsonBeanFactory.nullable boolean true 字段是否默认可空(String?)
flutterJsonBeanFactory.camelCase boolean true 是否将 JSON key 转换为驼峰命名
flutterJsonBeanFactory.autoFormat boolean false 生成文件后是否自动格式化代码

配置示例(settings.json)

{
  "flutterJsonBeanFactory.modelSuffix": "model",
  "flutterJsonBeanFactory.nullable": false,
  "flutterJsonBeanFactory.camelCase": true,
  "flutterJsonBeanFactory.autoFormat": true
}

项目配置 (pubspec.yaml)

在你的 pubspec.yaml 中添加 flutter_json 配置:

flutter_json:
  # 生成的文件存放路径(相对于项目根目录)
  generated_path: lib/generated/json/
  
  # 模块路径(多模块项目使用,单模块项目可省略)
  module_path: module_a
  
  # 是否生成 copyWith 方法(可选,默认 true)
  enableCopyWith: true
  
  # 是否生成 serialize/deserialize 控制(可选,默认 true)
  enableSerializeControl: true

多模块项目示例

如果你的项目结构是:

my_app/
├── module_a/
│   └── lib/
│       └── bean/
├── module_b/
│   └── lib/
│       └── bean/
└── pubspec.yaml

在 module_a/pubspec.yaml 中配置:

flutter_json:
  generated_path: lib/generated/json/
  module_path: module_a

⌨️ 快捷键

快捷键 功能 适用场景
Alt+J (Windows/Linux) / ⌥+J (Mac) JSON 转 Dart Bean 在 Dart 文件中,选中 JSON 或输入 JSON
Alt+H (Windows/Linux) / ⌥+H (Mac) 生成 Helper 文件 在包含 @JsonSerializable() 类的 Dart 文件中

快捷键自定义

如果快捷键冲突,可以在 VS Code 中自定义:

  1. 打开键盘快捷键设置(Ctrl+K Ctrl+S)
  2. 搜索 "FlutterJsonBeanFactoryX"
  3. 点击编辑图标修改快捷键

📚 使用示例

示例 1:简单对象

JSON:

{
  "id": 1,
  "title": "Hello World",
  "is_published": true
}

生成类名:ArticleEntity

输出:

@JsonSerializable()
class ArticleEntity {
  int? id;
  String? title;
  @JSONField(name: "is_published")
  bool? isPublished;

  ArticleEntity();

  factory ArticleEntity.fromJson(Map<String, dynamic> json) => _$ArticleEntityFromJson(json);

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

示例 2:嵌套对象和数组

JSON:

{
  "total": 100,
  "page": 1,
  "page_size": 20,
  "list": [
    {
      "product_id": "P001",
      "product_name": "iPhone 15",
      "price": 6999.00,
      "specs": {
        "color": "黑色",
        "storage": "256GB"
      }
    }
  ]
}

生成类名:ProductListEntity

输出:

@JsonSerializable()
class ProductListEntity {
  int? total;
  int? page;
  @JSONField(name: "page_size")
  int? pageSize;
  List<ProductListItem>? list;

  ProductListEntity();

  factory ProductListEntity.fromJson(Map<String, dynamic> json) => _$ProductListEntityFromJson(json);

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

@JsonSerializable()
class ProductListItem {
  @JSONField(name: "product_id")
  String? productId;
  @JSONField(name: "product_name")
  String? productName;
  double? price;
  ProductListItemSpecs? specs;

  ProductListItem();

  factory ProductListItem.fromJson(Map<String, dynamic> json) => _$ProductListItemFromJson(json);

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

@JsonSerializable()
class ProductListItemSpecs {
  String? color;
  String? storage;

  ProductListItemSpecs();

  factory ProductListItemSpecs.fromJson(Map<String, dynamic> json) => _$ProductListItemSpecsFromJson(json);

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

示例 3:数组数据

JSON:

[
  {"name": "Alice", "age": 25},
  {"name": "Bob", "age": 30}
]

扩展会自动识别数组结构,并生成包含 List 字段的包装类。


📁 项目结构

生成文件后的典型项目结构:

my_flutter_app/
├── lib/
│   ├── bean/                          # 你创建的 Dart Bean 类
│   │   └── user/
│   │       └── user_entity.dart
│   └── generated/                     # 生成的文件
│       └── json/
│           ├── base/
│           │   ├── json_field.dart    # JSON 字段注解
│           │   └── json_convert_content.dart  # 统一转换类
│           ├── user_entity.g.dart     # Helper 文件
│           └── ...
├── pubspec.yaml
└── ...

文件说明

文件 类型 说明
bean/*.dart 手动创建 包含 @JsonSerializable() 注解的实体类
base/json_field.dart 自动生成 JSON 字段注解定义
base/json_convert_content.dart 自动生成 统一 JSON 转换类
*.g.dart 自动生成 包含 fromJson/toJson 实现

重要:不要手动编辑 .g.dart 文件,它们会被自动覆盖。


❓ 常见问题

Q1: 快捷键无效怎么办?

A:

  1. 检查是否在 Dart 文件中
  2. 检查是否有快捷键冲突(查看 VS Code 右下角状态栏)
  3. 使用命令面板执行(Ctrl+Shift+P 或 ⌘+Shift+P)
  4. 重新安装扩展

Q2: 生成文件后没有代码提示?

A:

  1. 运行 flutter pub get 确保依赖已安装
  2. 运行 flutter pub run build_runner build 手动生成 .g.dart 文件
  3. 检查文件路径配置是否正确
  4. 重启 VS Code

Q3: 提示 "No classes that inherit JsonConvert were found"

A:

  1. 删除项目下的 .idea 目录
  2. 在 VS Code 中执行 "Dart: Restart Analysis Server"
  3. 重启 VS Code
  4. 重新生成 Helper 文件(Alt+H)

Q4: 如何在多模块项目中使用?

A: 在每个模块的 pubspec.yaml 中配置:

flutter_json:
  generated_path: lib/generated/json/
  module_path: 模块名

确保 module_path 与模块目录名一致。

Q5: 如何自定义 JSON 转换逻辑?

A: 创建自定义的 JsonConvert 类:

import 'package:your_app/generated/json/base/json_convert_content.dart';

class MyJsonConvert extends JsonConvert {
  @override
  T? asT<T extends Object?>(dynamic value) {
    try {
      String type = T.toString();
      if (type == "DateTime") {
        return DateTime.parse(value) as T;
      } else if (type == "Decimal") {
        return Decimal.parse(value) as T;
      }
      return super.asT<T>(value);
    } catch (e) {
      print('asT<$T> error: $e');
      return null;
    }
  }
}

// 在 main.dart 中初始化
void main() {
  jsonConvert = MyJsonConvert();
  runApp(MyApp());
}

Q6: 生成的字段都是可空的,如何改为非空?

A: 在 VS Code 设置中修改:

{
  "flutterJsonBeanFactory.nullable": false
}

或者在 pubspec.yaml 中:

flutter_json:
  nullable: false

Q7: 为什么选中了 JSON 文件但没反应?

A: 扩展只读取文本编辑器中选中的内容,不是文件管理器中选中的文件。需要:

  1. 打开 JSON 文件
  2. 选中文件内容(Ctrl+A 或 ⌘+A)
  3. 按 Alt+J

🔄 更新日志

v0.0.1 (2024-01-XX)

  • ✅ 完整移植 Android Studio 插件所有功能
  • ✅ 支持从 JSON 生成 Dart Bean 类
  • ✅ 支持生成 Helper 文件 (.g.dart)
  • ✅ 支持生成 json_convert_content.dart
  • ✅ 支持快捷键 Alt+J 和 Alt+H
  • ✅ 支持项目级配置 (pubspec.yaml)
  • ✅ 支持多模块项目
  • ✅ 支持自定义命名规则和可空类型

📚 相关链接

  • 项目 GitHub
  • Android Studio 插件版本
  • json_serializable 文档
  • JSON 转 Dart 在线工具

🤝 贡献指南

欢迎提交 Issue 和 Pull Request!

  1. Fork 本仓库
  2. 创建特性分支 (git checkout -b feature/amazing-feature)
  3. 提交更改 (git commit -m 'Add amazing feature')
  4. 推送到分支 (git push origin feature/amazing-feature)
  5. 创建 Pull Request

📄 许可证

MIT License - 详见 LICENSE 文件


🆘 获取帮助

  • 遇到问题?请提交 GitHub Issue
  • 需要功能?请提交 功能请求
  • 加入讨论:GitHub Discussions

Made with ❤️ by FlutterJsonBeanFactoryX Team

如果本扩展对你有帮助,请给项目一个 ⭐️ Star!


English Version

FlutterJsonBeanFactoryX (VS Code) Usage Documentation

📋 Table of Contents

  • Features
  • Installation
  • Quick Start
  • Core Features
  • Configuration
  • Keyboard Shortcuts
  • Examples
  • FAQ

✨ Features

FlutterJsonBeanFactoryX is a powerful VS Code extension that helps Flutter developers quickly generate type-safe Dart entity classes from JSON.

Key Features

  • 🚀 One-click generation: Generate Dart Bean classes from JSON strings
  • 🎯 Type-safe: Support generics, nested objects, List, Map, and complex types
  • ⚡ Smart conversion: Automatically convert JSON keys to camelCase
  • 🛠️ Flexible configuration: Support custom generation paths, class name suffixes, etc.
  • 🔧 Helper generation: Auto-generate fromJson/toJson helper methods
  • 📦 Modular support: Support multi-module project configuration

📦 Installation

Method 1: Install from VSIX (Recommended)

  1. Click "..." menu in Extensions sidebar
  2. Select "Install from VSIX..."
  3. Choose vscode-extension/flutter-json-bean-factory-x-vscode-0.0.1.vsix
  4. Restart VS Code

Method 2: Build from Source

cd vscode-extension
npm install
npm run build

Then in VS Code:

  1. Press F5 to start debugging (opens a new VS Code window)
  2. Or run vsce package to package as VSIX file

🚀 Quick Start

Step 1: Configure Your Project

Add configuration to your Flutter project's pubspec.yaml:

flutter_json:
  generated_path: lib/generated/json/
  module_path: module_a

Step 2: Install Dependencies

Ensure your project has these dependencies:

dependencies:
  json_annotation: ^4.8.1

dev_dependencies:
  json_serializable: ^6.7.1
  build_runner: ^2.4.6

Then run:

flutter pub get

Step 3: Generate Your First Bean

  1. Open any Dart file in the editor
  2. Select a JSON text (or copy to clipboard)
  3. Press Alt+J (Windows/Linux) or ⌥+J (Mac)
  4. Enter class name (e.g., UserEntity)
  5. Watch the magic! 🎉

⌨️ Keyboard Shortcuts

Shortcut Function When to Use
Alt+J / ⌥+J JSON to Dart Bean In Dart files, with JSON selected or input
Alt+H / ⌥+H Generate Helper Files In Dart files with @JsonSerializable() classes

⚙️ Configuration

VS Code Settings

Search "FlutterJsonBeanFactoryX" in VS Code settings:

Setting Type Default Description
flutterJsonBeanFactory.modelSuffix string "entity" Class name suffix, e.g., entity in UserEntity
flutterJsonBeanFactory.nullable boolean true Whether fields are nullable by default (String?)
flutterJsonBeanFactory.camelCase boolean true Whether to convert JSON keys to camelCase
flutterJsonBeanFactory.autoFormat boolean false Whether to auto-format code after generation

Project Configuration (pubspec.yaml)

flutter_json:
  generated_path: lib/generated/json/
  module_path: module_a

📚 Examples

Example 1: Simple Object

JSON:

{
  "id": 1,
  "title": "Hello World",
  "is_published": true
}

Generated Dart class:

@JsonSerializable()
class ArticleEntity {
  int? id;
  String? title;
  @JSONField(name: "is_published")
  bool? isPublished;

  ArticleEntity();

  factory ArticleEntity.fromJson(Map<String, dynamic> json) => _$ArticleEntityFromJson(json);

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

Example 2: Nested Objects and Arrays

See Chinese version above for detailed examples.


❓ FAQ

Q1: Shortcuts not working?

A:

  1. Check if you're in a Dart file
  2. Check for shortcut conflicts (look at VS Code status bar)
  3. Use Command Palette instead (Ctrl+Shift+P or ⌘+Shift+P)
  4. Reinstall the extension

Q2: No code hints after generation?

A:

  1. Run flutter pub get to ensure dependencies are installed
  2. Run flutter pub run build_runner build to manually generate .g.dart files
  3. Check if file path configuration is correct
  4. Restart VS Code

Q3: "No classes that inherit JsonConvert were found" error?

A:

  1. Delete the .idea directory in your project
  2. In VS Code, execute "Dart: Restart Analysis Server"
  3. Restart VS Code
  4. Regenerate Helper files (Alt+H)

Q4: Why selecting JSON file doesn't work?

A: The extension reads selected text in the text editor, not files selected in the file explorer. You need to:

  1. Open the JSON file
  2. Select the file content (Ctrl+A or ⌘+A)
  3. Press Alt+J

📄 License

MIT License


Made with ❤️ by FlutterJsonBeanFactoryX Team

If this extension helps you, please give the project a ⭐️ Star!

  • Contact us
  • Jobs
  • Privacy
  • Manage cookies
  • Terms of use
  • Trademarks
© 2026 Microsoft