如何编码Map<int, List<int>>类型映射?解决json.encode编码失败问题
Map<int, List<int>> in Dart Hey there! I see you're hitting a snag when trying to encode your Map<int, List<int>> with json.encode()—that "Converting object to an encodable object failed: _LinkedHashMap" error makes total sense once you know the root cause.
Why This Happens
JSON’s core specification only allows strings as object keys. Dart’s default json.encode() doesn’t automatically convert integer keys to strings, so it can’t process your Map<int, ...> directly, hence the encoding failure.
Solutions to Encode Your blocksMap
1. Convert Integer Keys to Strings (Simplest Approach)
Create a new map where all integer keys are converted to strings before encoding—this plays nice with JSON’s requirements:
import 'dart:convert'; void main() { Map<int, List<int>> blocksMap = { 0: [18, 117, 26, 200, 4, 30, 43, 110], 1: [18, 117, 26, 200, 4, 30, 43, 110], // ... your remaining entries }; // Convert int keys to strings Map<String, List<int>> stringKeyMap = blocksMap.map((key, value) => MapEntry(key.toString(), value)); // Now encode successfully String jsonString = json.encode(stringKeyMap); print(jsonString); }
2. Restore Integer Keys When Decoding
If you need to get back the original Map<int, List<int>> after decoding, parse the string keys back to integers:
// Decode the JSON string first Map<String, dynamic> decodedMap = json.decode(jsonString); // Convert string keys back to int and cast lists to List<int> Map<int, List<int>> restoredBlocksMap = decodedMap.map( (key, value) => MapEntry(int.parse(key), List<int>.from(value)) );
3. Custom Encoder (Advanced, Optional)
If you want to skip creating an intermediate map, you can write a tiny custom encoder—though this is overkill for most use cases:
String customEncodeMap(Map<int, List<int>> map) { return json.encode({ for (var entry in map.entries) entry.key.toString(): entry.value }); } // Usage String jsonString = customEncodeMap(blocksMap);
Quick Tips
- Double-check that your integer keys can safely convert to/from strings (no invalid numeric values when decoding).
- Using
List<int>.from(value)during decoding ensures you get a strongly-typed integer list instead of a dynamic one.
内容的提问来源于stack exchange,提问作者Titas Černiauskas

