2

I'm attempting to convert JSON that has strings for keys and string arrays for values.

From my understanding, this should work:

import 'dart:convert';

void main() {
  var jsonString = '{"key": ["1", "2", "3"]}';
  var data = json.decode(jsonString) as Map;
  var result = data.cast<String, List<String>>();
  print(result);
}

However I get the error that type 'List<dynamic>' is not a subtype of type 'List<String>' in type cast.

What's interesting, however, is that the following does correctly work:

import 'dart:convert';

void main() {
  var jsonString = '{"key": "value"}';
  var data = json.decode(jsonString) as Map;
  var result = data.cast<String, String>();
  print(result);
}

So, I assume that the .cast<> method introduced with Dart 2 doesn't know how to convert nested types that aren't simple types like String, int, or bool.

How would I convert this object to a Map<String, List<String>> without resorting to external libraries?

1 Answer 1

3

So, I assume that the .cast<> method introduced with Dart 2 doesn't know how to convert nested types that aren't simple types like String, int, or bool.

That's correct. It just does a one-level-deep shallow conversion. You can do the nested conversion yourself like:

void main() {
  var jsonString = '{"key": ["1", "2", "3"]}';
  var data = json.decode(jsonString) as Map;

  var result = data.map((key, value) =>
      MapEntry<String, List<String>>(key, List<String>.from(value)));
  print(result.runtimeType);
}

This is calling Map.map(). Sometimes Map.fromIterable() or Map.fromIterables() is a better fit. The collection types have a handful of methods like this to convert between different types.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.