Flutter类型化JSON数据获取插件typed_json_getters的使用

Flutter类型化JSON数据获取插件typed_json_getters的使用

特性

  • 类型安全访问:通过显式类型检索值。
  • 默认值:当键缺失时提供默认值。
  • 错误处理:在类型转换失败时抛出 FormatException
  • 嵌套键支持:使用点符号(.)访问嵌套的JSON属性。

安装

在你的 pubspec.yaml 文件中添加 typed_json_getters

dependencies:
  typed_json_getters: ^1.0.0

示例代码

main.dart

import 'package:typed_json_getters/typed_json_getters.dart';

void main() {
  // 示例JSON数据
  Map<String, dynamic> jsonData = {
    'user': {
      'id': 'u123',
      'name': 'Alice',
      'isActive': 'true',
      // 可以转换为布尔值的字符串
      'details': {
        'age': '30', // 可以转换为整数的字符串
        'height': 5.6, // 双精度值
        'weight': 'not available', // 无效的双精度值
      },
      'preferences': {
        'notifications': 'false', // 可以转换为布尔值的字符串
        'theme': 'dark',
      },
      'scores': ['100', '95', '80'],
      // 可以转换为整数的字符串列表
      'invalidScores': ['100', 'ninety-five', 80],
      // 混合列表,包含无效整数
      'address': null,
      // 空值
    },
    'meta': {
      'lastLogin': '2023-10-01T12:34:56Z',
      'signupCount': 'invalid', // 无效的整数
    },
  };

  // 使用 get<T> 获取带有默认值的数据
  String userId = jsonData.get<String>('user.id', defaultValue: '');
  String userName = jsonData.get<String>('user.name', defaultValue: 'Unknown');
  bool isActive = jsonData.get<bool>('user.isActive', defaultValue: false);
  int age = jsonData.get<int>('user.details.age', defaultValue: 0);
  double height = jsonData.get<double>('user.details.height', defaultValue: 0.0);
  double weight = jsonData.get<double>('user.details.weight', defaultValue: 0.0); // 转换失败
  bool notifications = jsonData.get<bool>('user.preferences.notifications', defaultValue: true);
  String theme = jsonData.get<String>('user.preferences.theme', defaultValue: 'light');
  List<int> scores = jsonData.getList<int>('user.scores', defaultValue: []);
  List<int> invalidScores = jsonData.getList<int>('user.invalidScores', defaultValue: []);
  Map<String, String> address = jsonData.getMap<String, String>('user.address', defaultValue: {}); // 空值
  int signupCount = jsonData.get<int>('meta.signupCount', defaultValue: 0); // 转换失败

  // 使用 getNullable<T> 获取可能为空的数据
  String? nickname = jsonData.getNullable<String>('user.nickname'); // 键不存在
  int? nullableAge = jsonData.getNullable<int>('user.details.age');
  double? nullableWeight = jsonData.getNullable<double>('user.details.weight'); // 转换失败
  bool? nullableNotifications = jsonData.getNullable<bool>('user.preferences.notifications');
  String? nullableTheme = jsonData.getNullable<String>('user.preferences.theme');
  List<int>? nullableScores = jsonData.getNullableList<int>('user.scores');
  List<int>? nullableInvalidScores = jsonData.getNullableList<int>('user.invalidScores'); // 转换失败
  Map<String, String>? nullableAddress = jsonData.getNullableMap<String, String>('user.address'); // 空值
  int? nullableSignupCount = jsonData.getNullable<int>('meta.signupCount'); // 转换失败

  // 使用点符号访问嵌套键
  String lastLogin = jsonData.get<String>('meta.lastLogin', defaultValue: 'Never');
  String innerValue1 = jsonData.get<String>('user.details.innerKey', defaultValue: 'No Value'); // 无效路径

  // 打印结果
  print('--- 使用 get<T> ---');
  print('User ID: $userId'); // 输出: User ID: u123
  print('User Name: $userName'); // 输出: User Name: Alice
  print('Is Active: $isActive'); // 输出: Is Active: true
  print('Age: $age'); // 输出: Age: 30
  print('Height: $height'); // 输出: Height: 5.6
  print('Weight: $weight'); // 输出: Weight: 0.0 (默认值由于转换失败)
  print('Notifications Enabled: $notifications'); // 输出: Notifications Enabled: false
  print('Theme: $theme'); // 输出: Theme: dark
  print('Scores: $scores'); // 输出: Scores: [100, 95, 80]
  print('Invalid Scores: $invalidScores'); // 输出: Invalid Scores: []
  print('Address: $address'); // 输出: Address: {}
  print('Signup Count: $signupCount'); // 输出: Signup Count: 0 (默认值由于转换失败)

  print('\n--- 使用 getNullable<T> ---');
  print('Nickname: $nickname'); // 输出: Nickname: null
  print('Nullable Age: $nullableAge'); // 输出: Nullable Age: 30
  print('Nullable Weight: $nullableWeight'); // 输出: Nullable Weight: null
  print('Nullable Notifications Enabled: $nullableNotifications'); // 输出: Nullable Notifications Enabled: false
  print('Nullable Theme: $nullableTheme'); // 输出: Nullable Theme: dark
  print('Nullable Scores: $nullableScores'); // 输出: Nullable Scores: [100, 95, 80]
  print('Nullable Invalid Scores: $nullableInvalidScores'); // 输出: Nullable Invalid Scores: null
  print('Nullable Address: $nullableAddress'); // 输出: Nullable Address: null
  print('Nullable Signup Count: $nullableSignupCount'); // 输出: Nullable Signup Count: null

  print('\n--- 嵌套键 ---');
  print('Last Login: $lastLogin'); // 输出: Last Login: 2023-10-01T12:34:56Z
  print('Inner Value1: $innerValue1'); // 输出: Inner Value1: No Value
}

更多关于Flutter类型化JSON数据获取插件typed_json_getters的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter类型化JSON数据获取插件typed_json_getters的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用typed_json_getters插件来处理类型化JSON数据的示例代码。

首先,确保你已经在pubspec.yaml文件中添加了typed_json_getters依赖:

dependencies:
  flutter:
    sdk: flutter
  typed_json_getters: ^x.y.z  # 请将 x.y.z 替换为最新版本号

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

接下来,我们假设有一个简单的JSON数据格式,如下所示:

{
  "id": 1,
  "name": "John Doe",
  "email": "john.doe@example.com"
}

我们将创建一个Flutter应用,并使用typed_json_getters来解析这个JSON数据。

  1. 定义数据模型

首先,我们需要定义一个数据模型类,并使用typed_json_getters注解。

import 'package:typed_json_getters/typed_json_getters.dart';

part 'user_model.g.dart'; // 用于生成getter方法的文件

@TypedJsonSerializable()
class User {
  final int id;
  final String name;
  final String email;

  User({required this.id, required this.name, required this.email});

  // 调用生成的fromJson构造函数
  factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);

  // 调用生成的toJson方法
  Map<String, dynamic> toJson() => _$UserToJson(this);
}
  1. 生成getter方法

运行以下命令来生成getter方法:

flutter pub run build_runner build

这将生成一个user_model.g.dart文件,其中包含从JSON到User对象的转换逻辑。

  1. 使用数据模型

现在,我们可以在Flutter应用中使用这个数据模型来解析JSON数据。

import 'package:flutter/material.dart';
import 'dart:convert';
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('Typed JSON Getters Example'),
        ),
        body: Center(
          child: FutureBuilder<User?>(
            future: fetchUser(),
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.done) {
                if (snapshot.hasError) {
                  return Text('Error: ${snapshot.error!}');
                }
                User? user = snapshot.data;
                return user == null
                    ? Text('No user data')
                    : Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          Text('ID: ${user!.id}'),
                          Text('Name: ${user.name}'),
                          Text('Email: ${user.email}'),
                        ],
                      );
              } else {
                return CircularProgressIndicator();
              }
            },
          ),
        ),
      ),
    );
  }

  Future<User?> fetchUser() async {
    String jsonData = '''
    {
      "id": 1,
      "name": "John Doe",
      "email": "john.doe@example.com"
    }
    ''';
    Map<String, dynamic> jsonMap = jsonDecode(jsonData);
    return User.fromJson(jsonMap);
  }
}

在上面的代码中,我们定义了一个简单的Flutter应用,它使用FutureBuilder来异步获取并显示用户数据。fetchUser函数模拟从JSON字符串解析用户数据,并使用User.fromJson方法将其转换为User对象。

这个示例展示了如何使用typed_json_getters插件来解析JSON数据并将其转换为强类型对象,从而在Flutter应用中更轻松地处理数据。

回到顶部