Flutter安全JSON解析插件safe_json的使用
Flutter安全JSON解析插件safe_json的使用
safe_json
该库的主要目标是在开发早期阶段通过获取JSON值时发现错误。
特性
- 安全地获取JSON/Map/Dictionary值,避免程序崩溃。
- 在失败时提供默认值。
- 记录带有描述和文件位置的错误日志。
示例
import 'package:safe_json/safe_json.dart';
class User {
final String name;
final int age;
final String school;
final List<String> articles;
final List<Vehicle> vehicles;
User(
{required this.name,
required this.age,
required this.school,
required this.articles,
required this.vehicles});
factory User.fromJson(Map<String, dynamic> json) {
return User(
name: json.safeString('name', defaultValue: 'John'), // 获取name字段,如果没有则返回默认值'John'
age: json.safeInt('age'), // 获取age字段,如果没有则返回null
school: json.safeString('school', defaultValue: 'MIT'), // 获取school字段,如果没有则返回默认值'MIT'
articles: json.safeList<String>('articles'), // 获取articles字段,如果没有则返回空列表
vehicles: json.safeList<Vehicle>('vehicles', itemParse: (json) => Vehicle.fromJson(json)), // 获取vehicles字段,并将每个元素解析为Vehicle对象
);
}
}
class Vehicle {
final String make;
final String model;
Vehicle({required this.make, required this.model});
factory Vehicle.fromJson(Map<String, dynamic> json) {
return Vehicle(
make: json.safeString('make'), // 获取make字段
model: json.safeString('model'), // 获取model字段
);
}
@override
String toString() {
return '$make $model'; // 返回车辆信息字符串
}
}
void main() {
Map<String, dynamic> json = {
'age': '30.0',
'articles': [
'article1',
'article2',
],
'vehicles': [
{'make': 'Toyota', 'model': 'Camry'},
{'make': 'Honda', 'model': 'Accord'},
],
};
User user = User.fromJson(json);
print(user.name); // 输出: John
print(user.age); // 输出: 30
print(user.school); // 输出: MIT
print(user.articles); // 输出: [article1, article2]
print(user.vehicles); // 输出: [Toyota Camry, Honda Accord]
}
// 如果想要在生产环境中禁用错误日志记录,可以设置为true
SafeJsonLibrary.skipLog = true;
// 设置控制台中显示的堆栈跟踪数量
SafeJsonLibrary.stackTraceCount = 1;
控制台日志
┌────────────────────────────────────────────────────────────────────────────────────────────────────
│ ⚠️ json['name'] return default value
├┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
│ value is null
│ package:your-project-name/models/user_model.dart:22:19
│ package:your-project-name/pages/home_page.dart:75:29
└────────────────────────────────────────────────────────────────────────────────────────────────────
更多关于Flutter安全JSON解析插件safe_json的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
1 回复
更多关于Flutter安全JSON解析插件safe_json的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
在Flutter中,处理JSON数据是开发过程中非常常见的任务。为了确保在解析JSON数据时的安全性和避免潜在的异常,可以使用 safe_json
插件。safe_json
提供了一种更安全的JSON解析方式,能够有效避免由于数据类型不匹配或字段缺失而导致的运行时错误。
安装 safe_json
插件
首先,你需要在 pubspec.yaml
文件中添加 safe_json
插件的依赖:
dependencies:
flutter:
sdk: flutter
safe_json: ^1.0.0 # 请使用最新版本
然后运行 flutter pub get
来安装依赖。
使用 safe_json
解析JSON
假设你有如下JSON数据:
{
"name": "John Doe",
"age": 30,
"isStudent": false,
"address": {
"city": "New York",
"zip": "10001"
},
"hobbies": ["reading", "swimming"]
}
你可以使用 safe_json
来安全地解析这个JSON数据。
1. 创建模型类
首先,创建一个Dart模型类来表示JSON数据结构:
import 'package:safe_json/safe_json.dart';
class User {
final String name;
final int age;
final bool isStudent;
final Address address;
final List<String> hobbies;
User({
required this.name,
required this.age,
required this.isStudent,
required this.address,
required this.hobbies,
});
factory User.fromJson(Map<String, dynamic> json) {
return User(
name: json.string('name') ?? 'Unknown',
age: json.int_('age') ?? 0,
isStudent: json.bool_('isStudent') ?? false,
address: Address.fromJson(json.map('address') ?? {}),
hobbies: json.list<String>('hobbies')?.cast<String>() ?? [],
);
}
}
class Address {
final String city;
final String zip;
Address({
required this.city,
required this.zip,
});
factory Address.fromJson(Map<String, dynamic> json) {
return Address(
city: json.string('city') ?? 'Unknown',
zip: json.string('zip') ?? 'Unknown',
);
}
}
2. 解析JSON数据
现在你可以使用 User.fromJson
方法来解析JSON数据:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'model/user.dart'; // 导入你的模型类
void main() {
const jsonString = '''
{
"name": "John Doe",
"age": 30,
"isStudent": false,
"address": {
"city": "New York",
"zip": "10001"
},
"hobbies": ["reading", "swimming"]
}
''';
Map<String, dynamic> jsonMap = jsonDecode(jsonString);
User user = User.fromJson(jsonMap);
runApp(MyApp(user: user));
}
class MyApp extends StatelessWidget {
final User user;
const MyApp({Key? key, required this.user}) : super(key: key);
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Safe JSON Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Name: ${user.name}'),
Text('Age: ${user.age}'),
Text('Is Student: ${user.isStudent}'),
Text('City: ${user.address.city}'),
Text('Zip: ${user.address.zip}'),
Text('Hobbies: ${user.hobbies.join(', ')}'),
],
),
),
),
);
}
}