diff static method
Performs a diff-algorithm on two JSON-like objects.
Returns a JSON-like List of JSON Patch operations to get from oldJson
to newJson
.
May throw a JsonPatchError if something goes wrong.
See https://tools.ietf.org/html/rfc6902 for more information.
Implementation
static List<Map<String, dynamic>> diff(dynamic oldJson, dynamic newJson) {
try {
// If both objects are null, no patch is required.
if (oldJson == null && newJson == null) {
return [];
}
// If the object was either null before or set to null now, replace the value.
if (oldJson == null || newJson == null) {
return [
{'op': 'replace', 'path': '', 'value': newJson}
];
}
// If the parameters are Maps, call the specialized function for objects.
if (oldJson is Map<String, dynamic> && newJson is Map<String, dynamic>) {
return _objectDiff(oldJson, newJson);
}
// If the parameters are List, call the specialized function for lists.
if (oldJson is List && newJson is List) {
return _listDiff(oldJson, newJson);
}
// If the runtime type changed, replace the value.
if (oldJson.runtimeType != newJson.runtimeType) {
return [
{'op': 'replace', 'path': '', 'value': newJson}
];
}
// For primitive types, use the == operator for comparison and replace if necessary.
if (oldJson != newJson) {
return [
{'op': 'replace', 'path': '', 'value': newJson}
];
}
// No difference found.
return [];
} catch (e) {
throw JsonPatchError('An unknown error occurred.');
}
}