Yes... that would be great. I'm a bit stuck here. @kevmoo it would be great if you could maybe add a comment here if you don't have the time to update the docs.
In my specific case, I need to convert Strings "123.45" to Decimal: Decimal.parse(value).
Fwiw, instead of trying to use the TypeHelper stuff you can just use the fromJson and toJson optional args on the JsonKey annotation to use a custom function. The main issue with that is you have to do it per field though.
@enyo – does the comment from @jakemac53 help?
@kevmoo yes definitely! That is a completely acceptable workaround for now.
Hey, sorry to open this again but I struggle with implementing the workaround...
what I try is something like:
@JsonKey(
name: "rate",
fromJson: Decimal.parse(value),
toJson: value.toString(),
)
Decimal rate;
fromJson doesn't work because of Arguments of a constant creation must be constant expressions. and toJson because of The argument type 'String' can't be assigned to the parameter type 'Function'.
I get that toJsoncan't work this way but also no Idea how to get this - and for fromJson I don't really know what the error message means tbh :/
Thx for any hints
Ok, it seems I figured it:
what I did now is:
@JsonKey(
name: "rate",
fromJson: _decimalFromJson,
toJson: _decimalToJson,
)
Decimal rate;
static Decimal _decimalFromJson(input) => Decimal.parse(input);
static String _decimalToJson(input) => input.toString();
it seems I did two mistakes, 1. is not using a function (could probably also be an anonymous function?) and 2. the static keyword is needed for some reason.
anyways, it works, great! :)
(not yet 100% tested but I wanted to update this first.)
Great to hear, @elmcrest
For others who are looking for away to do this with Decimal without having to create static methods that you have to reference everywhere. This is the way I did it. It would be helpful for there to be more documentation about how to write converters for types from other packages. I do not know if this is the "right way" but to me the implementation is cleaner.
@JsonSerializable(nullable: false)
@_DecimalStringConverter()
class DecimalClass {
Decimal myDecimal;
}
class _DecimalStringConverter implements JsonConverter<Decimal, String> {
const _DecimalStringConverter();
@override
Decimal fromJson(String json) => json == null ? null : Decimal.parse(json);
@override
String toJson(Decimal object) => object?.toString();
}
Honestly, I want to get away from expose the type helper stuff.
It's a lot of internal plumbing that's just got more complex.
Most helpful comment
For others who are looking for away to do this with Decimal without having to create static methods that you have to reference everywhere. This is the way I did it. It would be helpful for there to be more documentation about how to write converters for types from other packages. I do not know if this is the "right way" but to me the implementation is cleaner.