
com.tananaev.jsonpatch.operation.AddOperation 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
A Gson-based JSON patch standard implementation.
The newest version!
package com.tananaev.jsonpatch.operation;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.annotations.SerializedName;
import com.tananaev.jsonpatch.JsonPath;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class AddOperation extends AbsOperation {
@SerializedName("value")
public JsonElement data;
public AddOperation(JsonPath path, JsonElement data) {
this.data = data;
this.path = path;
}
@Override
public String getOperationName() {
return "add";
}
@Override
public void applyInPlace(InPlaceElementWrapper inPlaceElement){
JsonElement sourceElement = inPlaceElement.getJsonElement();
JsonElement item = path.head().navigate(sourceElement);
if ( item.isJsonObject() ){
item.getAsJsonObject().add(path.tail(),data);
} else if ( item.isJsonArray() ){
JsonArray array = item.getAsJsonArray();
int index = (path.tail().equals("-")) ? array.size() : Integer.valueOf(path.tail());
List temp = new ArrayList();
Iterator iter = array.iterator();
while (iter.hasNext()){
JsonElement stuff = iter.next();
iter.remove();
temp.add( stuff );
}
temp.add(index, data);
for ( JsonElement stuff: temp ){
array.add(stuff);
}
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy