[pve-devel] [PATCH dart_api_client 3/4] Add double serializer to handle String and int values
Aaron Lauterer
a.lauterer at proxmox.com
Wed Jun 23 12:04:43 CEST 2021
Adding a custom serializer for double values allows us to handle
situations in which the PVE API provides values in other types. The most
likely possibility is that numbers are formatted as string in the JSON
response which needs to be parsed to double.
We must also handle the situation that the value is an integer which
needs to be cast to double.
Signed-off-by: Aaron Lauterer <a.lauterer at proxmox.com>
---
lib/src/models/pve_double_serializer.dart | 28 +++++++++++++++++++++++
lib/src/models/serializers.dart | 2 ++
2 files changed, 30 insertions(+)
create mode 100644 lib/src/models/pve_double_serializer.dart
diff --git a/lib/src/models/pve_double_serializer.dart b/lib/src/models/pve_double_serializer.dart
new file mode 100644
index 0000000..3743a80
--- /dev/null
+++ b/lib/src/models/pve_double_serializer.dart
@@ -0,0 +1,28 @@
+import 'package:built_collection/built_collection.dart';
+import 'package:built_value/serializer.dart';
+
+class PveDoubleSerializer implements PrimitiveSerializer<double> {
+ final bool structured = false;
+ @override
+ final Iterable<Type> types = BuiltList<Type>([double]);
+ @override
+ final String wireName = 'double';
+
+ @override
+ Object serialize(Serializers serializers, double value,
+ {FullType specifiedType = FullType.unspecified}) {
+ return value;
+ }
+
+ @override
+ double deserialize(Serializers serializers, Object? serialized,
+ {FullType specifiedType = FullType.unspecified}) {
+ if (serialized is String) {
+ return double.parse(serialized);
+ }
+ if (serialized is int) {
+ return (serialized).toDouble();
+ }
+ return serialized as double;
+ }
+}
diff --git a/lib/src/models/serializers.dart b/lib/src/models/serializers.dart
index 2a0d501..0be80fc 100644
--- a/lib/src/models/serializers.dart
+++ b/lib/src/models/serializers.dart
@@ -3,6 +3,7 @@ import 'package:built_value/json_object.dart';
import 'package:built_value/serializer.dart';
import 'package:built_value/standard_json_plugin.dart';
import 'package:proxmox_dart_api_client/src/models/pve_bool_serializer.dart';
+import 'package:proxmox_dart_api_client/src/models/pve_double_serializer.dart';
import 'package:proxmox_dart_api_client/src/models/pve_int_serializer.dart';
import 'package:proxmox_dart_api_client/src/models/pve_string_serializer.dart';
import 'package:proxmox_dart_api_client/src/models/pve_datetime_from_epoch_serializer.dart';
@@ -43,6 +44,7 @@ part 'serializers.g.dart';
final Serializers serializers = (_$serializers.toBuilder()
..addPlugin(StandardJsonPlugin())
..add(PveBoolSerializer())
+ ..add(PveDoubleSerializer())
..add(PveIntSerializer())
..add(PveStringSerializer())
..add(PveDateTimeFromEpoch()))
--
2.30.2
More information about the pve-devel
mailing list