toJson method

Result<String, String> toJson({
  1. bool prettyPrint = false,
})

Implementation

Result<String, String> toJson({bool prettyPrint = false}) {
  try {
    final codec = Cbor()
      ..decodeFromBuffer(toCborList(forJson: true).getData());
    final jsonString = convertor.json.encode(codec.getDecodedData());
    // Remove the [] from the JSON string
    final result = jsonString.substring(1, jsonString.length - 1);
    if (prettyPrint) {
      const toJsonFromString = convertor.JsonDecoder();
      final json = toJsonFromString.convert(jsonString);
      const encoder = convertor.JsonEncoder.withIndent('  ');
      final formattedJson = encoder.convert(json);
      return Ok(formattedJson);
    } else {
      return Ok(result);
    }
  } on Exception catch (e) {
    return Err(e.toString());
  }
}