Flutter JSON序列化插件flexible_json_serializable的使用
Flutter JSON序列化插件flexible_json_serializable的使用
flexible_json_serializable
基于 package:json_serializable
,并处理将JSON解析为对象时不抛出异常。
支持类型(无需异常处理,可选类型)
BigInt
bool
DateTime
double
int
List
Map
Object
String
Uri
示例
左侧:json_serializable
右侧:flexible_json_serializable

完整示例代码
以下是一个完整的示例,展示如何使用 flexible_json_serializable
进行JSON序列化和反序列化。
// 导入必要的库
import 'package:flutter/material.dart';
import 'package:json_annotation/json_annotation.dart';
// 生成的文件部分
part 'example.g.dart';
// 使用 [@JsonSerializable](/user/JsonSerializable) 注解标记类
[@JsonSerializable](/user/JsonSerializable)()
class Person {
// 假设这些值存在于JSON中
final String firstName, lastName;
// 处理如果对应的JSON值不存在或为空的情况
final DateTime? dateOfBirth;
// 构造函数
Person({required this.firstName, required this.lastName, this.dateOfBirth});
// 将生成的 fromJson 方法连接到工厂构造函数
factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);
// 将生成的 toJson 方法连接到 toJson 方法
Map<String, dynamic> toJson() => _$PersonToJson(this);
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('flexible_json_serializable 示例'),
),
body: Center(
child: ExampleWidget(),
),
),
);
}
}
class ExampleWidget extends StatefulWidget {
[@override](/user/override)
_ExampleWidgetState createState() => _ExampleWidgetState();
}
class _ExampleWidgetState extends State<ExampleWidget> {
late Person person;
[@override](/user/override)
void initState() {
super.initState();
// 初始化 Person 对象
person = Person(
firstName: 'John',
lastName: 'Doe',
dateOfBirth: DateTime(1990, 1, 1),
);
// JSON 序列化
Map<String, dynamic> personJson = person.toJson();
print('序列化后的 JSON: $personJson');
// JSON 反序列化
Person decodedPerson = Person.fromJson(personJson);
print('反序列化后的 Person: ${decodedPerson.firstName} ${decodedPerson.lastName}');
}
[@override](/user/override)
Widget build(BuildContext context) {
return Container();
}
}
更多关于Flutter JSON序列化插件flexible_json_serializable的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
1 回复