Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart json.decode can't decode to Map<String, String>

Tags:

json

dart

My code:

import 'dart:convert';

String jsonString = '''{
"a": "g",
"b": "h",
"c": "j",
"d": "k"
}''';

Map<String, String> map = json.decode(jsonString);

Getting the error:

Unhandled exception:
type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Map<String, String>'
#0      main (file:///...)
#1      _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:298:32)
#2      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:171:12)

Map<String, dynamic> map ... and Map<String, Object> map ... Are working.

I am trying to de serialize in the end Map<String, Map> for different JSON and it gave me the same error so I have decided to first work with the basic which is the Map<String, String> to better understand what am I doing wrong

like image 634
Guy Luz Avatar asked Mar 03 '23 18:03

Guy Luz


1 Answers

To make sure the JSON is cast to the specified value use the Map.castFrom method.

So your code becomes

import 'dart:convert';

void main () {
  String jsonString = '''
{
  "a": "g",
  "b": "h",
  "c": "j",
  "d": "k"
}''';

  Map<String, String> map = Map.castFrom(json.decode(jsonString));
  print(map);
}

Note that if the types are incompatible it will throw. You should always consider handling that.

like image 197
Ajil O. Avatar answered Mar 16 '23 17:03

Ajil O.