Flutter JSON序列化与反序列化插件jsonize的使用

发布于 1周前 作者 sinazl 来自 Flutter

Flutter JSON序列化与反序列化插件jsonize的使用

简介

Jsonize 解决了将对象序列化为 JSON 格式并从 JSON 格式反序列化回对象的问题。此包不为你实现 toJsonfromJson 方法。你可以使用其他许多可用的包,如 json_serializable

使用

默认情况下,Jsonize 支持 EnumsDateTimeDuration 在数据结构中的任何位置的序列化。

import 'package:jsonize/jsonize.dart';

enum Color { red, blue, green, gray, yellow }

void main() {
  Jsonize.registerEnum(Color.values);

  List<dynamic> myList = [1, "Hello!", Color.blue, DateTime.now(), Duration(seconds: 30)];

  var jsonRep = Jsonize.toJson(myList);
  var myDeserializedList = Jsonize.fromJson(jsonRep);
  print(myDeserializedList);
}

Jsonize 还支持你自己的类。你可以注册类型或让你的类实现 JsonizableClonable 接口(用于类)和 JsonizableEnum 接口(用于保持枚举序列化安全)。

import 'package:jsonize/jsonize.dart';

enum Color with JsonizableEnum {
  /// The [jsonValue] must not change in time!
  red(10), // Can be numbers
  blue(20),
  green("myGreen"), // Can be strings as well
  gray(40),
  yellow(50);

  @override
  final dynamic jsonValue;
  const Color(this.jsonValue);
}

class MyClass implements Jsonizable<MyClass> {
  String? str;
  MyClass([this.str]);
  factory MyClass.empty() => MyClass();

  // Jsonizable implementation
  @override
  String get jsonClassCode => "mc";
  @override
  dynamic toJson() => str;
  @override
  MyClass? fromJson(value) => MyClass(value);
}

void main() {
  // Register enums and classes
  Jsonize.registerEnum(Color.values);
  Jsonize.registerClass(MyClass.empty());

  Map<String, dynamic> myMap = {
    "my_num": 1,
    "my_str": "Hello!",
    "my_color": Color.green,
    "my_dt": DateTime.now(),
    "my_duration": Duration(seconds: 30),
    "my_class": MyClass("here I am!")
  };
  var jsonRep = Jsonize.toJson(myMap);
  var hereIsMyMap = Jsonize.fromJson(jsonRep);
  print(hereIsMyMap);
}

Clonable 接口更紧凑,你只需要定义对象的字段。定义字段的一个优点是可以定义可选的默认值,这些默认值不会被设置到最终的 JSON 表示中以节省空间。由于必须在创建对象后设置对象变量,你可能不会将它们定义为 final。如果是 final 成员,你可以在 create 方法中通过 json 参数调用类构造函数。

import 'package:jsonize/jsonize.dart';

class ColorItem extends Clonable<ColorItem> {
  final String name;
  int r, g, b;
  ColorItem(this.name, {this.r = 0, this.g = 0, this.b = 0});
  factory ColorItem.empty() => ColorItem("");

  @override
  String toString() => "$name - $r.$g.$b";

  // Clonable implementation
  @override
  String get jsonClassCode => "colItem";

  @override
  ColorItem create(json) => ColorItem(json["name"]);

  @override
  CloneFields get fields => CloneFields([
        CloneField("name", getter: () => name, setter: (_) {}),
        CloneField("r", getter: () => r, setter: (v) => r = v, defaultValue: 0),
        CloneField("g", getter: () => g, setter: (v) => g = v, defaultValue: 0),
        CloneField("b", getter: () => b, setter: (v) => b = v, defaultValue: 0)
      ]);
}

void main() {
  // Register classes
  Jsonize.registerClass(ColorItem.empty());

  List myList = [
    ColorItem("Red", r: 255),
    ColorItem("Blue", b: 255),
    ColorItem("Gray", r: 128, g: 128, b: 128)
  ];

  // Zeros will not be serialized since they are defined as default value.
  // This way you might save json data storage space.
  var jsonRep = Jsonize.toJson(myList);
  var backToLife = Jsonize.fromJson(jsonRep);
  print(backToLife);
}

对于更复杂的情况,例如子类,请参阅示例部分。

Jsonize 方法

toJson

static String toJson(dynamic value,
      {String? indent,
      String? jsonClassToken,
      String? dtClassCode,
      DateTimeFormat dateTimeFormat = DateTimeFormat.string,
      String? durationClassCode,
      DurationFormat durationFormat = DurationFormat.microseconds,
      CallbackFunction? convertCallback,
      dynamic exParam})

将一个对象/对象结构转换为 JSON 字符串,并应用类标记以便恢复原始对象。

fromJson

static dynamic fromJson({dynamic value,
      {String? jsonClassToken,
      String? dtClassCode,
      DateTimeFormat dateTimeFormat = DateTimeFormat.string,
      String? durationClassCode,
      DurationFormat durationFormat = DurationFormat.microseconds,
      CallbackFunction? convertCallback,
      dynamic exParam,
      bool awaitNestedFutures = false}})

将 JSON 字符串转换回对象/对象结构。

registerEnum

static void registerEnum<T>(List<T> values,
      {String? jsonEnumCode, 
      EnumFormat enumFormat = EnumFormat.string,
      Enum? unknownEnumValue}) {

注册一个新的 Enum 类型。

registerClass

static void registerClass(Jsonizable object)

通过其实例注册一个新的 Jsonizable 类。

registerClasses

static void registerClasses(Iterable<Jsonizable> objects)

通过其实例注册新的 Jsonizable 类。

registerType

static void registerType(Type classType,
      String classTypeCode,
      ConvertFunction? toJsonFunc,
      ConvertFunction? fromJsonFunc)

更多关于Flutter JSON序列化与反序列化插件jsonize的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter JSON序列化与反序列化插件jsonize的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter中处理JSON数据的序列化和反序列化是一个常见的需求。jsonize 是一个可以帮助你简化这些操作的插件。尽管jsonize可能不是最知名的JSON处理库(Flutter社区中更常用的是json_serializationjson_annotationbuilt_value),但这里我会展示如何使用jsonize进行JSON的序列化和反序列化。

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

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

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

使用jsonize进行JSON序列化和反序列化

假设我们有一个简单的数据模型User

import 'package:jsonize/jsonize.dart';

@Jsonize
class User {
  String name;
  int age;
  String email;

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

  // 构造方法用于反序列化
  User.fromJson(Map<String, dynamic> json) {
    jsonize(this, json);
  }

  // 方法用于序列化
  Map<String, dynamic> toJson() {
    return jsonize(this);
  }
}

序列化

现在,我们可以创建一个User对象并将其转换为JSON字符串:

void main() {
  User user = User(name: "John Doe", age: 30, email: "john.doe@example.com");
  String jsonString = jsonEncode(user.toJson());
  print(jsonString);
  // 输出: {"name":"John Doe","age":30,"email":"john.doe@example.com"}
}

注意:jsonEncode 是 Dart 标准库中的函数,用于将 Dart 对象编码为 JSON 字符串。

反序列化

同样,我们可以将JSON字符串转换回User对象:

void main() {
  String jsonString = '{"name":"John Doe","age":30,"email":"john.doe@example.com"}';
  Map<String, dynamic> jsonMap = jsonDecode(jsonString);
  User user = User.fromJson(jsonMap);
  print(user.name); // 输出: John Doe
  print(user.age);  // 输出: 30
  print(user.email); // 输出: john.doe@example.com
}

注意:jsonDecode 也是 Dart 标准库中的函数,用于将 JSON 字符串解码为 Dart 对象(在这里是Map<String, dynamic>)。

完整示例

以下是一个完整的示例,展示了如何在一个Flutter应用中使用jsonize进行JSON的序列化和反序列化:

import 'package:flutter/material.dart';
import 'package:jsonize/jsonize.dart';
import 'dart:convert';

@Jsonize
class User {
  String name;
  int age;
  String email;

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

  User.fromJson(Map<String, dynamic> json) {
    jsonize(this, json);
  }

  Map<String, dynamic> toJson() {
    return jsonize(this);
  }
}

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('JSONize Example'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text('User Serialization and Deserialization'),
              ElevatedButton(
                onPressed: () {
                  User user = User(name: "John Doe", age: 30, email: "john.doe@example.com");
                  String jsonString = jsonEncode(user.toJson());
                  print('Serialized User: $jsonString');

                  Map<String, dynamic> jsonMap = jsonDecode(jsonString);
                  User deserializedUser = User.fromJson(jsonMap);
                  print('Deserialized User: ${deserializedUser.name}, ${deserializedUser.age}, ${deserializedUser.email}');
                },
                child: Text('Serialize and Deserialize'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

这个示例展示了如何在Flutter应用中创建一个简单的UI,通过点击按钮来序列化和反序列化一个User对象,并在控制台中打印结果。

回到顶部