I have a service that is sending me a list of values and after parsing with the 'dart:convert json.decode' I get a List < dynamic > json as such:
(values) [ 0.23, 0.2, 0, 0.43 ]
When I try to parse the values to 'double', I get a parsing error
double value = values[2] // error
Because if we check the .runtimeType of each element we can see that we have the following
[double, double, int, double]
So, how can I avoid '0' being interpreted as int? I would like to avoid using a function like this:
double jsonToDouble(dynamic value) {
if(value.runtimeType == int) {
return (value as int).toDouble();
}
return value;
}
You can add some special logic to the JSON decoding by constructing your own codec with a reviver. This callback will be invoked for every property in a map or item in a List.
final myJsonCodec = new JsonCodec.withReviver((dynamic key, dynamic value) {
if (value is int) return value.toDouble();
return value;
});
However, you will always get a List<dynamic>
from dart:covert
, whether or not all of your number types are doubles or ints. Depending on what version of dart you are on you may be able to use List.cast
to convert to a List<double>
.
List<double> values = oldValues.cast<double>();
If that isn't available, you can create a new List<double>
and add your values to it so that the runtime type is correctly set.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With