0

I'm sending the JSON as string from response.body, but getting "Unhandled Exception: type 'String' is not a subtype of type 'Map<String, dynamic>' in type cast" error after mapping in Flutter/Dart. If i write the JSON manually, the code works. But if i get the JSON as string from parameter, getting cast error.

I tried to cast return value to List but extractedData should change i guess, stucked here. "s" is JSON string.

The getVacDates function is for getting only date or total values from the JSON like [10/14/21, 10/15/21, 10/16/21...] by mapping.

static List<String> getVacDates(String s) {
    final newList = jsonEncode(s);
    final extractedData = jsonDecode(newList) as Map<String, dynamic>;
    final china= extractedData['timeline'].map((e) => e["date"]);

    List<String> StringList = china.cast<String>();
    print(StringList);
    return StringList;
  }

For information the JSON is:

{"country":"USA","timeline":

[{"total":409571117,"daily":757824,"totalPerHundred":121,"dailyPerMillion":2253,"date":"10/14/21"},

    {"total":410559043,"daily":743873,"totalPerHundred":122,"dailyPerMillion":2212,"date":"10/15/21"},    

    {"total":411028977,"daily":737439,"totalPerHundred":122,"dailyPerMillion":2193,"date":"10/16/21"},    

    {"total":411287235,"daily":731383,"totalPerHundred":122,"dailyPerMillion":2175,"date":"10/17/21"}]}

Simplified program:

responseVac = await http.get('https://disease.sh/v3/covid-19/vaccine/coverage/countries/usa?lastdays=3');
        var data = MyFile.myFunction(xxx, yyy, responseVac.body);

in MyFile:

static ChartsData myFunction(String xxx, bool yyy, String responseVac) {

List<String> getVacDates(String s) =>
          [for (final data in jsonDecode(s)['timeline']) data['date'] as String];

      print(getVacDates(responseVac));
osunkaya
  • 93
  • 1
  • 1
  • 9
  • What is the point of doing `newList = jsonEncode(s)` and then right after do `jsonDecode(newList)`? Also, your JSON String would end up returning a `List` when parsed since the JSON starts with `[`. – julemand101 Nov 13 '21 at 21:22
  • because it's needed for serialization mapping solution from https://stackoverflow.com/a/69955879/17393881 to get dates, total values as list. (i don't have other working solution so i used it) – osunkaya Nov 13 '21 at 21:29
  • Eh no? That was an example showing how you could convert your data as a JSON string and then later decode it back. It was not an example of you should be doing these two steps inside the same method. In this example you have given, you already have a JSON formatted String (s) so you should not do `jsonEncode(s)`. – julemand101 Nov 13 '21 at 21:34
  • but i couldn't able to map it original json. also i found to cause of the problem. if i write the json manually the code works but if i get from parameter, having cast error. Changed to "Object s" still same. – osunkaya Nov 13 '21 at 21:48
  • Are you sure about the posted JSON? It ends with `}` but starts with `[` which makes it invalid but could also indicate this part of the JSON is cut of from some other JSON structure? – julemand101 Nov 13 '21 at 21:49
  • sorry i added first line {"country":"USA","timeline": – osunkaya Nov 13 '21 at 21:53

1 Answers1

0

Not entire sure what you are trying to get but is it something like this?

import 'dart:convert';

void main() {
  print(getVacDates(jsonString)); // [10/14/21, 10/15/21, 10/16/21, 10/17/21]
}

List<String> getVacDates(String s) => [
      for (final timeline in jsonDecode(s)['timeline'])
        timeline['date'] as String
    ];

const jsonString = '''{
  "country": "USA",
  "timeline": [
    {
      "total": 409571117,
      "daily": 757824,
      "totalPerHundred": 121,
      "dailyPerMillion": 2253,
      "date": "10/14/21"
    },
    {
      "total": 410559043,
      "daily": 743873,
      "totalPerHundred": 122,
      "dailyPerMillion": 2212,
      "date": "10/15/21"
    },
    {
      "total": 411028977,
      "daily": 737439,
      "totalPerHundred": 122,
      "dailyPerMillion": 2193,
      "date": "10/16/21"
    },
    {
      "total": 411287235,
      "daily": 731383,
      "totalPerHundred": 122,
      "dailyPerMillion": 2175,
      "date": "10/17/21"
    }
  ]
}''';
julemand101
  • 28,470
  • 5
  • 52
  • 48
  • i corrected the json, it has second level and need to get all dates and totals sepeately. my code is working with manual json, but some how with sending to parameter having cast error. – osunkaya Nov 13 '21 at 21:54
  • @osunkaya Updated example to work with the recently provided JSON. – julemand101 Nov 13 '21 at 21:56
  • maybe related with https://stackoverflow.com/questions/64748976/dart-can-not-use-a-response-body-as-a-string – osunkaya Nov 13 '21 at 22:44
  • @osunkaya Please provide more details in your example so it matches your problem. E.g. add a small program which reproduces your issue. Also, please provide full stacktrace of your errors. – julemand101 Nov 13 '21 at 23:20
  • `Unhandled Exception: type '_InternalLinkedHashMap' is not a subtype of type 'Iterable'` – osunkaya Nov 13 '21 at 23:48
  • responseVac = await http.get('https://disease.sh/v3/covid-19/vaccine/coverage/countries/usa?lastdays=3'); var data = MyFile.myFunction(xxx, yyy, responseVac.body); **in MyFile:** static ChartsData myFunction(String xxx, bool yyy, String responseVac) { List getVacDates(String s) => [for (final data in jsonDecode(s)['timeline']) data['date'] as String]; print(getVacDates(responseVac)); added to question post too. – osunkaya Nov 13 '21 at 23:52
  • At the late night and tiredness my api response was not "?fullData=true", i noticed and corrected, now fully working. thanks. – osunkaya Nov 14 '21 at 08:02