json - 如何在 Dart 中使用 json_annotation 将 Uint8List 序列化为 json?

标签 json flutter dart

我做了一个简单的类,它有一个 Uint8List成员:

import "package:json_annotation/json_annotation.dart";
part "openvpn.g.dart";

@JsonSerializable()
class OpenVPN extends VPN {
  OpenVPN(Uint8List profile) {
    this.profile = profile;
  }
  /...
  Uint8List profile = null;
但是,当在其上运行 build runner 以生成 json 序列化程序时,我得到:
Could not generate `fromJson` code for `profile`.
None of the provided `TypeHelper` instances support the defined type.
package:my_app/folder/openvpn.dart:19:13
   ╷
19 │   Uint8List profile = null;
   │             ^^^^^^^
有没有办法为这种类型编写我自己的序列化程序?或者有更简单的方法吗?
我不想在 json 文件上有一个字符串,我想有实际的字节。这是一个小文件,因此可以将其作为字节数组存储在 json 中。

最佳答案

为 Uint8List 添加自定义 JSON 转换器

import 'dart:typed_data';
import 'package:json_annotation/json_annotation.dart';

class Uint8ListConverter implements JsonConverter<Uint8List, List<int>> {
  const Uint8ListConverter();

  @override
  Uint8List fromJson(List<int> json) {
    if (json == null) {
      return null;
    }

    return Uint8List.fromList(json);
  }

  @override
  List<int> toJson(Uint8List object) {
    if (object == null) {
      return null;
    }

    return object.toList();
  }
}
使用 Uint8ListConverter在 Uint8List 属性上。
在你的情况下:
import 'package:json_annotation/json_annotation.dart';
import 'dart:typed_data';
import 'package:.../uint8_list_converter.dart';

part 'open_vpn.g.dart';

@JsonSerializable(explicitToJson: true)
class OpenVPN {
  OpenVPN({this.profile});

  @Uint8ListConverter()
  Uint8List profile = null;

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

  Map<String, dynamic> toJson() => _$OpenVPNToJson(this);
}
在根项目路径中,从终端运行以生成 open_vpn.g.dart部分文件:flutter packages pub run build_runner build --delete-conflicting-outputs

关于json - 如何在 Dart 中使用 json_annotation 将 Uint8List 序列化为 json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63716036/

相关文章:

ios - objective-c JSON 文字,嵌套 - 最优雅的解决方案?

ios - flutter/iOS : Could not determine bundle id

types - 即使我将其转换为完全相同的类,变量类型也会返回 false

sql - 元素类型 'Iterable<Widget>' 无法分配给列表类型 'Widget'

flutter - 这个以Classname为前缀的class-const-Syntax在Dart中是什么意思?

javascript - JSON 数据未保存在 WebAPI 中

json - 如何正确解码不同类型的数组?

json - 在 Nancy FX 的 json 响应中省略空值

flutter - Flutter:通过另一个小部件中的键隐藏/显示一个小部件

dart - 在 Dart 中添加 map 中的所有值