s k
s k

Reputation: 5212

Flutter: jsonDecode unable to decode key to integer value

The json string is for illustrative purpose only. The actual json string is much larger. I hope the key can be parsed directly into int instead of String

String json = "{ \"1\": \"test\", \"2\": \"test\" }";
Map<int, String> map = jsonDecode(json);

Error:

_TypeError (type '_Map<String, dynamic>' is not a subtype of type 'Map<int, String>')

Upvotes: 0

Views: 199

Answers (1)

Peter Koltai
Peter Koltai

Reputation: 9754

Im not aware of a solution to do this without converting the map. After jsonDecode you can use forEach to go through the map elements and convert them and store in another map:

import 'dart:convert';

void main() {
  String json = "{ \"1\": \"test1\", \"2\": \"test2\" }";

  final rawMap = jsonDecode(json);
  final convertedMap = <int, String>{};

  rawMap
      .forEach((key, value) => convertedMap[int.parse(key)] = value.toString());
  print(convertedMap[2]);
}

Upvotes: 1

Related Questions