jsonTreeDecode method

  1. @override
Map<K, V> jsonTreeDecode(
  1. Object? json, {
  2. JsonDecodingContext? context,
})
override

Converts the argument (a JSON tree) into an instance of T.

Valid nodes in JSON trees

The method takes 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 json = '2020-12-31';
  final kind = DateKind();
  kind.jsonTreeDecode(json); // --> 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
Map<K, V> jsonTreeDecode(Object? json, {JsonDecodingContext? context}) {
  context ??= JsonDecodingContext();
  if (json is Map) {
    final result = <K, V>{};
    for (var entry in json.entries) {
      final key = context.decode(
        entry.key,
        kind: keyKind,
      );
      final value = context.decode(
        entry.value,
        kind: valueKind,
      );
      result[key] = value;
    }
    return result;
  } else {
    throw context.newGraphNodeError(
      value: json,
      reason: 'Expected JSON map',
    );
  }
}