Skip to content

Add JsonObject class and serializer. #146

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 10, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
## 0.5.6

- Add serializer for "DateTime" fields.
- Add JsonObject class and serializer.
- Add convenience methods Seralizers.serializeWith and deserializeWith.
- Add example for using StandardJsonPlugin.

## 0.5.5

Expand Down
202 changes: 202 additions & 0 deletions built_value/lib/json_object.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,202 @@
// Copyright (c) 2017, Google Inc. Please see the AUTHORS file for details.
// All rights reserved. Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

import 'package:collection/collection.dart';

/// A JSON value.
///
/// This class is suitable for use in built_value fields. When serialized it
/// maps directly onto JSON values.
///
/// Deep operator== and hashCode are provided, meaning the contents of a
/// List or Map is used for equality and hashing.
///
/// List and Map classes are wrapped in [UnmodifiableListView] and
/// [UnmodifiableMapView] so they won't be modifiable via this object. You
/// must ensure that no updates are made via the original reference, as a
/// copy is not made.
abstract class JsonObject {
/// The value, which may be a bool, a List, a Map, a num or a String.
Object get value;

/// Whether the value is a [bool].
bool get isBool => false;

/// The value as a [bool], or throw if not.
bool get asBool => throw new StateError('Not a bool.');

/// Whether the value is a [List].
bool get isList => false;

/// The value as a [List], or throw if not.
List get asList => throw new StateError('Not a List.');

/// Whether the value is a [Map].
bool get isMap => false;

/// The value as a [Map], or throw if not.
Map get asMap => throw new StateError('Not a Map.');

/// Whether the value is a [num].
bool get isNum => false;

/// The value as a [num], or throw if not.
num get asNum => throw new StateError('Not a num.');

/// Whether the value is a [String].
bool get isString => false;

/// The value as a [String], or throw if not.
String get asString => throw new StateError('Not a String.');

/// Instantiates with [value], which must be a bool, a List, a Map, a num
/// or a String. Otherwise, an [ArgumentError] is thrown.
factory JsonObject(Object value) {
if (value is num) {
return new NumJsonObject(value);
} else if (value is String) {
return new StringJsonObject(value);
} else if (value is bool) {
return new BoolJsonObject(value);
} else if (value is List<Object>) {
return new ListJsonObject(value);
} else if (value is Map<String, Object>) {
return new MapJsonObject(value);
} else {
throw new ArgumentError.value(value, 'value',
'Must be bool, List<Object>, Map<String, Object>, num or String.');
}
}

JsonObject._();

@override
String toString() {
return value.toString();
}
}

/// A [JsonObject] holding a bool.
class BoolJsonObject extends JsonObject {
@override
final bool value;

BoolJsonObject(this.value) : super._();

@override
bool get isBool => true;

@override
bool get asBool => value;

@override
bool operator ==(dynamic other) {
if (identical(other, this)) return true;
if (other is! BoolJsonObject) return false;
return value == other.value;
}

@override
int get hashCode => value.hashCode;
}

/// A [JsonObject] holding a List.
class ListJsonObject extends JsonObject {
@override
final List<Object> value;

ListJsonObject(List<Object> value)
: this.value = new UnmodifiableListView<Object>(value),
super._();

@override
bool get isList => true;

@override
List<Object> get asList => value;

@override
bool operator ==(dynamic other) {
if (identical(other, this)) return true;
if (other is! ListJsonObject) return false;
return const DeepCollectionEquality().equals(value, other.value);
}

@override
int get hashCode => const DeepCollectionEquality().hash(value);
}

/// A [JsonObject] holding a Map.
class MapJsonObject extends JsonObject {
@override
final Map<String, Object> value;

MapJsonObject(Map<String, Object> value)
: this.value = new UnmodifiableMapView(value),
super._();

@override
bool get isMap => true;

@override
Map<String, Object> get asMap => value;

@override
bool operator ==(dynamic other) {
if (identical(other, this)) return true;
if (other is! MapJsonObject) return false;
return const DeepCollectionEquality().equals(value, other.value);
}

@override
int get hashCode => const DeepCollectionEquality().hash(value);
}

/// A [JsonObject] holding a num.
class NumJsonObject extends JsonObject {
@override
final num value;

NumJsonObject(this.value) : super._();

@override
bool get isNum => true;

@override
num get asNum => value;

@override
bool operator ==(dynamic other) {
if (identical(other, this)) return true;
if (other is! NumJsonObject) return false;
return value == other.value;
}

@override
int get hashCode => value.hashCode;
}

/// A [JsonObject] holding a String.
class StringJsonObject extends JsonObject {
@override
final String value;

StringJsonObject(this.value) : super._();

@override
bool get isString => true;

@override
String get asString => value;

@override
bool operator ==(dynamic other) {
if (identical(other, this)) return true;
if (other is! StringJsonObject) return false;
return value == other.value;
}

@override
int get hashCode => value.hashCode;
}
12 changes: 12 additions & 0 deletions built_value/lib/serializer.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import 'package:built_collection/built_collection.dart';
import 'package:built_value/src/date_time_serializer.dart';
import 'package:built_value/src/json_object_serializer.dart';
import 'package:built_value/src/num_serializer.dart';
import 'package:quiver/core.dart';

Expand Down Expand Up @@ -36,6 +37,7 @@ abstract class Serializers {
..add(new DateTimeSerializer())
..add(new DoubleSerializer())
..add(new IntSerializer())
..add(new JsonObjectSerializer())
..add(new NumSerializer())
..add(new StringSerializer())
..addBuilderFactory(
Expand Down Expand Up @@ -72,6 +74,11 @@ abstract class Serializers {
Object serialize(Object object,
{FullType specifiedType: FullType.unspecified});

/// Convenience method for when you know the type you're serializing.
/// Specify the type by specifying its [Serializer] class. Equivalent to
/// calling [serialize] with a `specifiedType`.
Object serializeWith<T>(Serializer<T> serializer, T object);

/// Deserializes [serialized].
///
/// A [Serializer] must have been provided for every type the object uses.
Expand All @@ -81,6 +88,11 @@ abstract class Serializers {
Object deserialize(Object serialized,
{FullType specifiedType: FullType.unspecified});

/// Convenience method for when you know the type you're deserializing.
/// Specify the type by specifying its [Serializer] class. Equivalent to
/// calling [deserialize] with a `specifiedType`.
T deserializeWith<T>(Serializer<T> serializer, Object serialized);

/// Creates a new builder for the type represented by [fullType].
///
/// For example, if [fullType] is `BuiltList<int, String>`, returns a
Expand Down
13 changes: 13 additions & 0 deletions built_value/lib/src/built_json_serializers.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

import 'package:built_collection/built_collection.dart';
import 'package:built_value/serializer.dart';
import 'package:built_value/serializer.dart';

/// Default implementation of [Serializers].
class BuiltJsonSerializers implements Serializers {
Expand All @@ -27,6 +28,18 @@ class BuiltJsonSerializers implements Serializers {
BuiltJsonSerializers._(this._typeToSerializer, this._wireNameToSerializer,
this._typeNameToSerializer, this._builderFactories, this._plugins);

@override
T deserializeWith<T>(Serializer<T> serializer, Object serialized) {
return deserialize(serialized,
specifiedType: new FullType(serializer.types.first)) as T;
}

@override
Object serializeWith<T>(Serializer<T> serializer, T object) {
return serialize(object,
specifiedType: new FullType(serializer.types.first));
}

@override
Object serialize(Object object,
{FullType specifiedType: FullType.unspecified}) {
Expand Down
34 changes: 34 additions & 0 deletions built_value/lib/src/json_object_serializer.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// Copyright (c) 2017, Google Inc. Please see the AUTHORS file for details.
// All rights reserved. Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

import 'package:built_collection/built_collection.dart';
import 'package:built_value/json_object.dart';
import 'package:built_value/serializer.dart';

class JsonObjectSerializer implements PrimitiveSerializer<JsonObject> {
final bool structured = false;
@override
final Iterable<Type> types = new BuiltList<Type>([
JsonObject,
BoolJsonObject,
ListJsonObject,
MapJsonObject,
NumJsonObject,
StringJsonObject,
]);
@override
final String wireName = 'JsonObject';

@override
Object serialize(Serializers serializers, JsonObject jsonObject,
{FullType specifiedType: FullType.unspecified}) {
return jsonObject.value;
}

@override
JsonObject deserialize(Serializers serializers, Object serialized,
{FullType specifiedType: FullType.unspecified}) {
return new JsonObject(serialized);
}
}
7 changes: 5 additions & 2 deletions built_value/lib/standard_json_plugin.dart
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import 'package:built_collection/built_collection.dart';
import 'package:built_value/json_object.dart';
import 'package:built_value/serializer.dart';
import 'dart:convert' show JSON;

Expand All @@ -25,14 +26,16 @@ class StandardJsonPlugin implements SerializerPlugin {

@override
Object afterSerialize(Object object, FullType specifiedType) {
return object is List && specifiedType.root != BuiltList
return object is List &&
specifiedType.root != BuiltList &&
specifiedType.root != JsonObject
? _toMap(object, _alreadyHasStringKeys(specifiedType))
: object;
}

@override
Object beforeDeserialize(Object object, FullType specifiedType) {
return object is Map
return object is Map && specifiedType.root != JsonObject
? _toList(object, _alreadyHasStringKeys(specifiedType))
: object;
}
Expand Down
Loading