decodeUnion method
Decode a JSON object that is expected to be one of several choices,
where the choices are disambiguated by the contents of the field field
.
decoders
is a map from each possible string in the field to the decoder
that should be used to decode the JSON object.
Implementation
Object decodeUnion(String jsonPath, Object? jsonData, String field,
Map<String, JsonDecoderCallback> decoders) {
if (jsonData is Map) {
if (!jsonData.containsKey(field)) {
throw missingKey(jsonPath, field);
}
var disambiguatorPath = '$jsonPath[${json.encode(field)}]';
var disambiguator = decodeString(disambiguatorPath, jsonData[field]);
var decoder = decoders[disambiguator];
if (decoder == null) {
throw mismatch(
disambiguatorPath, 'One of: ${decoders.keys.toList()}', jsonData);
}
return decoder(jsonPath, jsonData);
} else {
throw mismatch(jsonPath, 'Map', jsonData);
}
}