
com.github.fge.jsonpatch.MoveOperation Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of json-patch Show documentation
Show all versions of json-patch Show documentation
JSON Patch (RFC 6902) and JSON Merge Patch (RFC 7386) implementation in Java
/*
* Copyright (c) 2013, Francis Galiegue
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Lesser GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Lesser GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
package com.github.fge.jsonpatch;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode;
import com.github.fge.jackson.jsonpointer.JsonPointer;
/**
* JSON Patch {@code move} operation
*
* For this operation, {@code from} points to the value to move, and {@code
* path} points to the new location of the moved value.
*
* As for {@code add}:
*
*
* - the value at the destination path is either created or replaced;
* - it is created only if the immediate parent exists;
* - {@code -} appends at the end of an array.
*
*
* It is an error condition if {@code from} does not point to a JSON value.
*
*
* The specification adds another rule that the {@code from} path must not be
* an immediate parent of {@code path}. Unfortunately, that doesn't really work.
* Consider this patch:
*
*
* { "op": "move", "from": "/0", "path": "/0/x" }
*
*
* Even though {@code /0} is an immediate parent of {@code /0/x}, when this
* patch is applied to:
*
*
* [ "victim", {} ]
*
*
* it actually succeeds and results in the patched value:
*
*
* [ { "x": "victim" } ]
*
*/
public final class MoveOperation
extends DualPathOperation
{
@JsonCreator
public MoveOperation(@JsonProperty("from") final JsonPointer from,
@JsonProperty("path") final JsonPointer path)
{
super(from, path);
}
@Override
public JsonNode apply(final JsonNode node)
throws JsonPatchException
{
if (from.equals(path))
return node.deepCopy();
final JsonNode movedNode = from.path(node);
if (movedNode.isMissingNode())
throw new JsonPatchException(JsonPatchMessages.NO_SUCH_PATH);
final JsonPatchOperation remove = new RemoveOperation(from);
final JsonPatchOperation add = new AddOperation(path, movedNode);
return add.apply(remove.apply(node));
}
@Override
public String toString()
{
return "move: " + super.toString();
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy