public boolean set(Object rootObject, Object value) { if (rootObject == null) { return false; } init(); Object currentObject = rootObject; Object parentObject = null; for (int i = 0; i < segments.length; ++i) { if (i == segments.length - 1) { parentObject = currentObject; break; } currentObject = segments[i].eval(this, rootObject, currentObject); if (currentObject == null) { break; } } if (parentObject == null) { return false; } Segement lastSegement = segments[segments.length - 1]; if (lastSegement instanceof PropertySegement) { PropertySegement propertySegement = (PropertySegement) lastSegement; propertySegement.setValue(this, parentObject, value); return true; } if (lastSegement instanceof ArrayAccessSegement) { return ((ArrayAccessSegement) lastSegement).setValue(this, parentObject, value); } throw new UnsupportedOperationException(); }
@SuppressWarnings({"rawtypes", "unchecked"}) public void arrayAdd(Object rootObject, Object... values) { if (values == null || values.length == 0) { return; } if (rootObject == null) { return; } init(); Object currentObject = rootObject; Object parentObject = null; for (int i = 0; i < segments.length; ++i) { if (i == segments.length - 1) { parentObject = currentObject; } currentObject = segments[i].eval(this, rootObject, currentObject); } Object result = currentObject; if (result == null) { throw new JSONPathException("value not found in path " + path); } if (result instanceof Collection) { Collection collection = (Collection) result; for (Object value : values) { collection.add(value); } return; } Class<?> resultClass = result.getClass(); Object newResult; if (resultClass.isArray()) { int length = Array.getLength(result); Object descArray = Array.newInstance(resultClass.getComponentType(), length + values.length); System.arraycopy(result, 0, descArray, 0, length); for (int i = 0; i < values.length; ++i) { Array.set(descArray, length + i, values[i]); } newResult = descArray; } else { throw new UnsupportedOperationException(); } Segement lastSegement = segments[segments.length - 1]; if (lastSegement instanceof PropertySegement) { PropertySegement propertySegement = (PropertySegement) lastSegement; propertySegement.setValue(this, parentObject, newResult); return; } if (lastSegement instanceof ArrayAccessSegement) { ((ArrayAccessSegement) lastSegement).setValue(this, parentObject, newResult); return; } throw new UnsupportedOperationException(); }