Skip to content

Instantly share code, notes, and snippets.

@Dragorn421
Created April 16, 2017 16:29
Show Gist options
  • Save Dragorn421/f77d63b0f1deb53e800b914608680ca8 to your computer and use it in GitHub Desktop.
Save Dragorn421/f77d63b0f1deb53e800b914608680ca8 to your computer and use it in GitHub Desktop.
@SuppressWarnings("unchecked")
public static <T extends JsonElement> T merge(final T obj1, final T obj2)
{
if(obj1 == null)
return clone(obj2);
if(obj2 == null)
return clone(obj1);
if(obj1 instanceof JsonObject)
{
final Map<String, JsonElement> merged = new HashMap<>();
obj2.getAsJsonObject().entrySet().forEach(entry -> merged.put(entry.getKey(), entry.getValue()));
obj1.getAsJsonObject().entrySet().forEach(entry -> merged.put(entry.getKey(), merge(entry.getValue(), obj2.getAsJsonObject().get(entry.getKey()))));
final JsonObject mergedJson = new JsonObject();
merged.forEach((key, value) -> mergedJson.add(key, value));
return (T) mergedJson;
}
if(obj1 instanceof JsonArray)
{
final List<JsonElement> merged = new ArrayList<>();
obj1.getAsJsonArray().forEach(element -> merged.add(element));
obj2.getAsJsonArray().forEach(element -> {
if(!merged.contains(element))
merged.add(element);
});
final JsonArray mergedJson = new JsonArray();
merged.forEach(mergedJson::add);
return (T) mergedJson;
}
if(obj1 instanceof JsonPrimitive)
return obj1;
throw new UnsupportedOperationException("Cannot merge " + obj1.getClass().getName());
}
@SuppressWarnings("unchecked")
public static <T extends JsonElement> T clone(final T json)
{
if(json instanceof JsonObject)
{
final JsonObject copyOf = (JsonObject) json;
final JsonObject clone = new JsonObject();
copyOf.entrySet().forEach(entry -> clone.add(entry.getKey(), clone(entry.getValue())));
return (T) clone;
}
if(json instanceof JsonArray)
{
final JsonArray copyOf = (JsonArray) json;
final JsonArray clone = new JsonArray();
copyOf.forEach(element -> clone.add(clone(element)));
return (T) clone;
}
if(json instanceof JsonPrimitive)
{
return json;
}
throw new UnsupportedOperationException("Cannot clone " + json.getClass().getName());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment