Skip to content

Json sealed

sealedclassJson

Annotations: @immutable

An immutable JSON value.

The sealed subtypes are JNull, JBoolean, JNumber, JString, JArray, and JObject. Use the static factory methods to construct values and fold / foldWith for exhaustive pattern matching.

Properties

hashCode no setter override

intgethashCode

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.

Implementation
dart
@override
int get hashCode => fold(
  () => 0,
  (boolean) => boolean.hashCode,
  (number) => number.hashCode,
  (string) => string.hashCode,
  (ilist) => ilist.hashCode,
  (object) => object.keys.hashCode * object.values.hashCode,
);

hcursor no setter

HCursorgethcursor

Returns an HCursor positioned at the root of this value.

Implementation
dart
HCursor get hcursor => HCursor.fromJson(this);

isArray no setter

boolgetisArray

Returns true if this value is a JArray.

Implementation
dart
bool get isArray;

isBoolean no setter

boolgetisBoolean

Returns true if this value is a JBoolean.

Implementation
dart
bool get isBoolean;

isNull no setter

boolgetisNull

Returns true if this value is JNull.

Implementation
dart
bool get isNull;

isNumber no setter

boolgetisNumber

Returns true if this value is a JNumber.

Implementation
dart
bool get isNumber;

isObject no setter

boolgetisObject

Returns true if this value is a JObject.

Implementation
dart
bool get isObject;

isString no setter

boolgetisString

Returns true if this value is a JString.

Implementation
dart
bool get isString;

runtimeType no setter inherited

TypegetruntimeType

A representation of the runtime type of the object.

Inherited from Object.

Implementation
dart
external Type get runtimeType;

Methods

asArray()

Option<IList<Json>>asArray()

Returns Some with the elements if this is JArray, otherwise None.

Implementation
dart
Option<IList<Json>> asArray();

asBoolean()

Option<bool>asBoolean()

Returns Some with the boolean if this is JBoolean, otherwise None.

Implementation
dart
Option<bool> asBoolean();

asNull()

Option<Unit>asNull()

Returns Some with Unit if this is JNull, otherwise None.

Implementation
dart
Option<Unit> asNull();

asNumber()

Option<num>asNumber()

Returns Some with the number if this is JNumber, otherwise None.

Implementation
dart
Option<num> asNumber();

asObject()

Option<JsonObject>asObject()

Returns Some with the JsonObject if this is JObject, otherwise None.

Implementation
dart
Option<JsonObject> asObject();

asString()

Option<String>asString()

Returns Some with the string if this is JString, otherwise None.

Implementation
dart
Option<String> asString();

deepDropNullValues()

JsondeepDropNullValues()

Returns a copy with all JNull values removed recursively.

Implementation
dart
Json deepDropNullValues() => foldWith(_DropNullFolder());

deepMerge()

JsondeepMerge(Jsonthat)

Recursively merges that into this value.

Object fields from this value take precedence; fields present in both are merged recursively. If either value is not a JObject, returns that.

Implementation
dart
Json deepMerge(Json that) => (asObject(), that.asObject())
    .mapN(
      (lhs, rhs) => fromJsonObject(
        lhs.toIList().foldLeft(
          rhs,
          (acc, kv) => rhs
              .get(kv.$1)
              .fold(
                () => acc.add(kv.$1, kv.$2),
                (r) => acc.add(kv.$1, kv.$2.deepMerge(r)),
              ),
        ),
      ),
    )
    .getOrElse(() => that);

dropNullValues()

JsondropNullValues()

Returns a copy with all top-level object fields whose value is JNull removed.

Implementation
dart
Json dropNullValues() => mapObject((a) => a.filter((keyValue) => !keyValue.$2.isNull));

fold()

Afold<A>(AFunction()jsonNull,AFunction(bool)jsonBoolean,AFunction(num)jsonNumber,AFunction(String)jsonString,AFunction(IList<Json>)jsonArray,AFunction(JsonObject)jsonObject,);

Pattern-matches this value, calling the corresponding function for each subtype.

Implementation
dart
A fold<A>(
  Function0<A> jsonNull,
  Function1<bool, A> jsonBoolean,
  Function1<num, A> jsonNumber,
  Function1<String, A> jsonString,
  Function1<IList<Json>, A> jsonArray,
  Function1<JsonObject, A> jsonObject,
) => switch (this) {
  JNull _ => jsonNull(),
  final JBoolean b => jsonBoolean(b.value),
  final JNumber n => jsonNumber(n.value),
  final JString s => jsonString(s.value),
  final JArray a => jsonArray(a.value),
  final JObject o => jsonObject(o.value),
};

foldWith()

AfoldWith<A>(JsonFolder<A>folder)

Dispatches to folder based on the runtime subtype of this value.

Implementation
dart
A foldWith<A>(JsonFolder<A> folder);

mapArray()

JsonmapArray(IList<Json>Function(IList<Json>)f)

If this is JArray, returns a JArray with the elements mapped through f; otherwise returns this unchanged.

Implementation
dart
Json mapArray(Function1<IList<Json>, IList<Json>> f);

mapBoolean()

JsonmapBoolean(boolFunction(bool)f)

If this is JBoolean, returns a JBoolean with the value mapped through f; otherwise returns this unchanged.

Implementation
dart
Json mapBoolean(Function1<bool, bool> f);

mapNumber()

JsonmapNumber(numFunction(num)f)

If this is JNumber, returns a JNumber with the value mapped through f; otherwise returns this unchanged.

Implementation
dart
Json mapNumber(Function1<num, num> f);

mapObject()

JsonmapObject(JsonObjectFunction(JsonObject)f)

If this is JObject, returns a JObject with the JsonObject mapped through f; otherwise returns this unchanged.

Implementation
dart
Json mapObject(Function1<JsonObject, JsonObject> f);

mapString()

JsonmapString(StringFunction(String)f)

If this is JString, returns a JString with the value mapped through f; otherwise returns this unchanged.

Implementation
dart
Json mapString(Function1<String, String> f);

noSuchMethod() inherited

dynamicnoSuchMethod(Invocationinvocation)

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);

printWith()

StringprintWith(Printerprinter)

Renders this value using printer.

Implementation
dart
String printWith(Printer printer) => printer.print(this);

toString() inherited

StringtoString()

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();

withArray()

JsonwithArray(JsonFunction(IList<Json>)f)

If this is JArray, returns f(elements); otherwise returns this unchanged.

Implementation
dart
Json withArray(Function1<IList<Json>, Json> f);

withBoolean()

JsonwithBoolean(JsonFunction(bool)f)

If this is JBoolean, returns f(value); otherwise returns this unchanged.

Implementation
dart
Json withBoolean(Function1<bool, Json> f);

withNull()

JsonwithNull(JsonFunction()f)

If this is JNull, returns f(); otherwise returns this unchanged.

Implementation
dart
Json withNull(Function0<Json> f);

withNumber()

JsonwithNumber(JsonFunction(num)f)

If this is JNumber, returns f(value); otherwise returns this unchanged.

Implementation
dart
Json withNumber(Function1<num, Json> f);

withObject()

JsonwithObject(JsonFunction(JsonObject)f)

If this is JObject, returns f(object); otherwise returns this unchanged.

Implementation
dart
Json withObject(Function1<JsonObject, Json> f);

withString()

JsonwithString(JsonFunction(String)f)

If this is JString, returns f(value); otherwise returns this unchanged.

Implementation
dart
Json withString(Function1<String, Json> f);

Operators

operator ==() override

booloperator ==(Objectother)

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.

Implementation
dart
@override
bool operator ==(Object other) {
  return fold(
    () => other is JNull,
    (boolean) => other is JBoolean && other.value == boolean,
    (number) => other is JNumber && other.value == number,
    (string) => other is JString && other.value == string,
    (ilist) => other is JArray && other.value == ilist,
    (object) => other is JObject && other.value == object,
  );
}

Static Methods

arr()

Jsonarr(Iterable<Json>values)

Creates a JArray from an Iterable.

Implementation
dart
static Json arr(Iterable<Json> values) => JArray(IList.fromDart(values));

arrI()

JsonarrI(IList<Json>values)

Creates a JArray from an IList.

Implementation
dart
static Json arrI(IList<Json> values) => JArray(values);

boolean()

Jsonboolean(boolvalue)

Creates a JBoolean.

Implementation
dart
static Json boolean(bool value) => JBoolean(value);

decode()

Either<Error,A>decode<A>(Stringinput,Decoder<A>decoder)

Parses input and decodes the result with decoder in one step.

Implementation
dart
static Either<Error, A> decode<A>(String input, Decoder<A> decoder) =>
    parse(input).leftMap<Error>(identity).flatMap((a) => decoder.decode(a));

decodeBytes()

Either<Error,A>decodeBytes<A>(Uint8Listinput,Decoder<A>decoder)

Parses input bytes and decodes the result with decoder in one step.

Implementation
dart
static Either<Error, A> decodeBytes<A>(Uint8List input, Decoder<A> decoder) =>
    parseBytes(input).leftMap<Error>(identity).flatMap((a) => decoder.decode(a));

deepMergeAll()

JsondeepMergeAll(Iterable<Json>json)

Recursively merges all values in json left-to-right, starting from an empty object.

Implementation
dart
static Json deepMergeAll(Iterable<Json> json) =>
    json.fold(Json.obj([]), (a, b) => a.deepMerge(b));

fromJsonObject()

JsonfromJsonObject(JsonObjectvalue)

Wraps a JsonObject in a JObject.

Implementation
dart
static Json fromJsonObject(JsonObject value) => JObject(value);

number()

Jsonnumber(numvalue)

Creates a JNumber, or Null if value is non-finite.

Implementation
dart
static Json number(num value) => value.isFinite ? JNumber(value) : Null;

obj()

Jsonobj(Iterable<Record>fields)

Creates a JObject from an iterable of (key, value) pairs.

Implementation
dart
static Json obj(Iterable<(String, Json)> fields) =>
    fromJsonObject(JsonObject.fromIterable(fields));

parse()

Either<ParsingFailure,Json>parse(Stringinput)

Parses input as JSON, returning Right(json) or Left(failure).

Implementation
dart
static Either<ParsingFailure, Json> parse(String input) => dawn.Parser.parseFromString(input);

parseBytes()

Either<ParsingFailure,Json>parseBytes(Uint8Listinput)

Parses input as UTF-8 JSON bytes, returning Right(json) or Left(failure).

Implementation
dart
static Either<ParsingFailure, Json> parseBytes(Uint8List input) =>
    dawn.Parser.parseFromBytes(input);

str()

Jsonstr(Stringvalue)

Creates a JString.

Implementation
dart
static Json str(String value) => JString(value);

Constants

False

constJsonFalse

The singleton JSON false value.

Implementation
dart
static const Json False = JBoolean(false);

Null

constJsonNull

The singleton JSON null value.

Implementation
dart
static const Json Null = JNull();

True

constJsonTrue

The singleton JSON true value.

Implementation
dart
static const Json True = JBoolean(true);