I'm trying to implement a function that applies a JSON-PATCH (RFC 6902) to an object annotated with JSON-B.
I've come to the following solution:
/**
* Applies a JSON patch to a JSON-B annotated object, and returns a resulting patched version of the object.
*
* @param object the object to patch.
* @param type the runtime type of the object to patch.
* @param patch the patch to apply to the object.
* @param <T> the generic type of the object to patch.
* @return a patched version of the object.
*/
private <T> T patch(T object, Class<T> type, JsonArray patch) {
JsonPatch jsonPatch = Json.createPatchBuilder(patch).build();
Jsonb jsonb = JsonbBuilder.create();
String jsonRepresentation = jsonb.toJson(object); // serialize the object into a JSON representation
try (JsonReader jsonReader = Json.createReader(new StringReader(jsonRepresentation))) {
return jsonb.fromJson(
jsonPatch.apply(
jsonReader.read() // deserialize the JSON representation into a JSON-P structure
).toString(), // apply the patch and serialize the resulting JSON-P structure into a JSON representation
type
); // deserialize the JSON representation into the original form
}
}
The problem with this approach is the number of serializations / deserializations that occurs in the process, not to mention that the implementation is not fluid.
Did I miss something in the API to simplify the implementation of this patching function, or is it just that a bridge is missing between JSON-B and JSON like:
jsonb.toJsonStructure(object); // would return a JSON Processing JsonStructure