Skip to content

JsonCodec final

final class JsonCodec extends Codec<Object?, String>

A JsonCodec encodes JSON objects to strings and decodes strings to JSON objects.

Examples:

dart
var encoded = json.encode([1, 2, { "a": null }]);
var decoded = json.decode('["foo", { "bar": 499 }]');

Inheritance

Object → Codec<S, T>JsonCodec

Constructors

JsonCodec() const

const JsonCodec({
  (Object? Function(Object? key, Object? value))? reviver,
  (Object? Function(dynamic object))? toEncodable,
})

Creates a JsonCodec with the given reviver and encoding function.

The reviver function is called during decoding. It is invoked once for each object or list property that has been parsed. The key argument is either the integer list index for a list property, the string map key for object properties, or null for the final result.

If reviver is omitted, it defaults to returning the value argument.

The toEncodable function is used during encoding. It is invoked for values that are not directly encodable to a string (a value that is not a number, boolean, string, null, list or a map with string keys). The function must return an object that is directly encodable. The elements of a returned list and values of a returned map do not need to be directly encodable, and if they aren't, toEncodable will be used on them as well. Please notice that it is possible to cause an infinite recursive regress in this way, by effectively creating an infinite data structure through repeated call to toEncodable.

If toEncodable is omitted, it defaults to a function that returns the result of calling .toJson() on the unencodable object.

Implementation
dart
const JsonCodec({
  Object? reviver(Object? key, Object? value)?,
  Object? toEncodable(dynamic object)?,
}) : _reviver = reviver,
     _toEncodable = toEncodable;

JsonCodec.withReviver()

JsonCodec.withReviver(dynamic Function(Object? key, Object? value) reviver)

Creates a JsonCodec with the given reviver.

The reviver function is called once for each object or list property that has been parsed during decoding. The key argument is either the integer list index for a list property, the string map key for object properties, or null for the final result.

Implementation
dart
JsonCodec.withReviver(dynamic reviver(Object? key, Object? value))
  : this(reviver: reviver);

Properties

decoder no setter override

JsonDecoder get decoder

Returns the decoder of this, converting from T to S.

It may be stateful and should not be reused.

Implementation
dart
JsonDecoder get decoder {
  if (_reviver == null) return const JsonDecoder();
  return JsonDecoder(_reviver);
}

encoder no setter override

JsonEncoder get encoder

Returns the encoder from S to T.

It may be stateful and should not be reused.

Implementation
dart
JsonEncoder get encoder {
  if (_toEncodable == null) return const JsonEncoder();
  return JsonEncoder(_toEncodable);
}

hashCode no setter inherited

int get hashCode

The hash code for this object.

A hash code is a single integer which represents the state of the object that affects operator == comparisons.

All objects have hash codes. The default hash code implemented by Object represents only the identity of the object, the same way as the default operator == implementation only considers objects equal if they are identical (see identityHashCode).

If operator == is overridden to use the object state instead, the hash code must also be changed to represent that state, otherwise the object cannot be used in hash based data structures like the default Set and Map implementations.

Hash codes must be the same for objects that are equal to each other according to operator ==. The hash code of an object should only change if the object changes in a way that affects equality. There are no further requirements for the hash codes. They need not be consistent between executions of the same program and there are no distribution guarantees.

Objects that are not equal are allowed to have the same hash code. It is even technically allowed that all instances have the same hash code, but if clashes happen too often, it may reduce the efficiency of hash-based data structures like HashSet or HashMap.

If a subclass overrides hashCode, it should override the operator == operator as well to maintain consistency.

Inherited from Object.

Implementation
dart
external int get hashCode;

inverted no setter inherited

Codec<String, Object?> get inverted

Inverts this.

The encoder and decoder of the resulting codec are swapped.

Inherited from Codec.

Implementation
dart
Codec<T, S> get inverted => _InvertedCodec<T, S>(this);

runtimeType no setter inherited

Type get runtimeType

A representation of the runtime type of the object.

Inherited from Object.

Implementation
dart
external Type get runtimeType;

Methods

decode() override

dynamic decode(
  String source, {
  (Object? Function(Object? key, Object? value))? reviver,
})

Parses the string and returns the resulting Json object.

The optional reviver function is called once for each object or list property that has been parsed during decoding. The key argument is either the integer list index for a list property, the string map key for object properties, or null for the final result.

The default reviver (when not provided) is the identity function.

Implementation
dart
dynamic decode(
  String source, {
  Object? reviver(Object? key, Object? value)?,
}) {
  reviver ??= _reviver;
  if (reviver == null) return decoder.convert(source);
  return JsonDecoder(reviver).convert(source);
}

encode() override

String encode(Object? value, {(Object? Function(dynamic object))? toEncodable})

Converts value to a JSON string.

If value contains objects that are not directly encodable to a JSON string (a value that is not a number, boolean, string, null, list or a map with string keys), the toEncodable function is used to convert it to an object that must be directly encodable.

If toEncodable is omitted, it defaults to a function that returns the result of calling .toJson() on the unencodable object.

Implementation
dart
String encode(Object? value, {Object? toEncodable(dynamic object)?}) {
  toEncodable ??= _toEncodable;
  if (toEncodable == null) return encoder.convert(value);
  return JsonEncoder(toEncodable).convert(value);
}

fuse() inherited

Codec<Object?, R> fuse<R>(Codec<String, R> other)

Fuses this with other.

When encoding, the resulting codec encodes with this before encoding with other.

When decoding, the resulting codec decodes with other before decoding with this.

In some cases one needs to use the inverted codecs to be able to fuse them correctly. That is, the output type of this (T) must match the input type of the second codec other.

Examples:

dart
final jsonToBytes = json.fuse(utf8);
List<int> bytes = jsonToBytes.encode(["json-object"]);
var decoded = jsonToBytes.decode(bytes);
assert(decoded is List && decoded[0] == "json-object");

var inverted = json.inverted;
var jsonIdentity = json.fuse(inverted);
var jsonObject = jsonIdentity.encode(["1", 2]);
assert(jsonObject is List && jsonObject[0] == "1" && jsonObject[1] == 2);

Inherited from Codec.

Implementation
dart
&#47;&#47; TODO(floitsch): use better example with line-splitter once that one is
&#47;&#47; in this library.
Codec<S, R> fuse<R>(Codec<T, R> other) {
  return _FusedCodec<S, T, R>(this, other);
}

noSuchMethod() inherited

dynamic noSuchMethod(Invocation invocation)

Invoked when a nonexistent method or property is accessed.

A dynamic member invocation can attempt to call a member which doesn't exist on the receiving object. Example:

dart
dynamic object = 1;
object.add(42); // Statically allowed, run-time error

This invalid code will invoke the noSuchMethod method of the integer 1 with an Invocation representing the .add(42) call and arguments (which then throws).

Classes can override noSuchMethod to provide custom behavior for such invalid dynamic invocations.

A class with a non-default noSuchMethod invocation can also omit implementations for members of its interface. Example:

dart
class MockList<T> implements List<T> {
  noSuchMethod(Invocation invocation) {
    log(invocation);
    super.noSuchMethod(invocation); // Will throw.
  }
}
void main() {
  MockList().add(42);
}

This code has no compile-time warnings or errors even though the MockList class has no concrete implementation of any of the List interface methods. Calls to List methods are forwarded to noSuchMethod, so this code will log an invocation similar to Invocation.method(#add, [42]) and then throw.

If a value is returned from noSuchMethod, it becomes the result of the original invocation. If the value is not of a type that can be returned by the original invocation, a type error occurs at the invocation.

The default behavior is to throw a NoSuchMethodError.

Inherited from Object.

Implementation
dart
@pragma("vm:entry-point")
@pragma("wasm:entry-point")
external dynamic noSuchMethod(Invocation invocation);

toString() inherited

String toString()

A string representation of this object.

Some classes have a default textual representation, often paired with a static parse function (like int.parse). These classes will provide the textual representation as their string representation.

Other classes have no meaningful textual representation that a program will care about. Such classes will typically override toString to provide useful information when inspecting the object, mainly for debugging or logging.

Inherited from Object.

Implementation
dart
external String toString();

Operators

operator ==() inherited

bool operator ==(Object other)

The equality operator.

The default behavior for all Objects is to return true if and only if this object and other are the same object.

Override this method to specify a different equality relation on a class. The overriding method must still be an equivalence relation. That is, it must be:

  • Total: It must return a boolean for all arguments. It should never throw.

  • Reflexive: For all objects o, o == o must be true.

  • Symmetric: For all objects o1 and o2, o1 == o2 and o2 == o1 must either both be true, or both be false.

  • Transitive: For all objects o1, o2, and o3, if o1 == o2 and o2 == o3 are true, then o1 == o3 must be true.

The method should also be consistent over time, so whether two objects are equal should only change if at least one of the objects was modified.

If a subclass overrides the equality operator, it should override the hashCode method as well to maintain consistency.

Inherited from Object.

Implementation
dart
external bool operator ==(Object other);