jsonTreeEncode method

  1. @override
Object? jsonTreeEncode(
  1. Map<K, V> value, {
  2. JsonEncodingContext? context,
})
override

Converts the argument into a JSON tree.

Valid nodes in JSON trees

The method returns a tree, where nodes are instances of:

  • null
  • bool
  • double
  • String
  • List, where items are valid nodes.
  • Map<String,Object?>, where keys are strings and values are valid nodes.

Errors

Thrown errors are subclasses of GraphNodeError, which describes which node in the input graph caused the error.

Examples

import 'package:kind/kind.dart';

void main() {
  final date = Date(2020, 12, 31);
  final kind = DateKind();
  kind.jsonTreeEncode(date); // --> '2020-12-31'
}

Implementing this method

Implementations must use context to:

  • Serialize other values.
  • Construct errors.

If context is null, implementations must construct one with JsonDecodingContext().

Implementation

@override
Object? jsonTreeEncode(Map<K, V> value, {JsonEncodingContext? context}) {
  context ??= JsonEncodingContext();
  final jsonObject = <String, Object?>{};
  for (var entry in value.entries) {
    final key = entry.key;
    final value = entry.value;
    final keyJson = keyKind.jsonTreeEncode(key);
    if (keyJson is! String) {
      throw context.newGraphNodeError(
        value: key,
        reason:
            'Expected key to be encoded as JSON string, but was encoded as ${keyJson.runtimeType}: $key',
      );
    }
    final valueJson = context.encode(value, kind: valueKind);
    jsonObject[keyJson] = valueJson;
  }
  return jsonObject;
}