MATLAB: Deserialized containers.Map keys exceed max name length

containers.mapdeserializationMATLABnamelengthmax

While trying to desirialize a containers.Map I get a cell2struct error in matlab.internal.json.makeStructure due to duplicate field names. The duplicate field names stem from Map keys which are more than 70 chars long and differ only in the last chars (I have no influence on the length of these keys). I use jsonencode/jsondecode to de/serialize the Map. Is there a simple workaround for this problem or am I missing an option or s.th.?

Best Answer

To put it kindly, the json serialisation and deserialisation code in matlab is not very mature nor very thoroughly tested. For a while it did not even always generate json compliant code.
I guess you found another bug with that code, so you ought to report it to mathworks (or I'll do it later today). From past experience, it won't be fixed until the next version at least.
I doubt that there is any settings/options to avoid the bug. The only thing I can suggest is to serialise and deserialise the keys and values yourself:
%serialisation
jsonencode(struct('keys', yourmap.keys, 'values', yourmap.values);
%deserialisation
kvp = jsondecode(somejson);
restoredmap = containers.Map(kvp.Keys, kvp.Values);
Obviously if the map is part of a larger object it is a problem as you can't pass the object directly to jsonencode anymore. Whereas in earlier version the jsondecode/encode code was implemented as m files so you could fix the bugs yourselves, it is now built-in leaving you no chance to override the behaviour for maps.