encodeObject<T> static method

JsonString encodeObject<T>(
  1. T value, {
  2. JsonObjectEncoder<T>? encoder,
  3. bool checkIfJsonable = true,
})

Constructs a JsonString converting value into a valid JSON Object.

If T implements Jsonable interface, the result returned by .toJson() is used during the conversion. If not, the encoder function must be provided.

To turn the runtime Jsonable check off, set checkIfJsonable to false.

Implementation

static JsonString encodeObject<T>(
  T value, {
  JsonObjectEncoder<T>? encoder,
  bool checkIfJsonable = true,
}) {
  if (checkIfJsonable && encoder == null && value is! Jsonable?) {
    throw JsonEncodingError('[T] must mix in Jsonable when `checkIfJsonable` '
        'is set to true and an encoder is not provided');
  }
  return wrapJsonUtilOperation(() {
    final encodable = EncodableValue.fromObject<T, Map<String, dynamic>?>(
      value,
      encoder: encoder,
    );
    return JsonString._(encodable.encode(), null);
  });
}