Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart: How to json decode '0' as double

Tags:

dart

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;
}
like image 939
Abarroso Avatar asked Dec 14 '22 17:12

Abarroso


1 Answers

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.

like image 141
Jonah Williams Avatar answered Jan 28 '23 06:01

Jonah Williams