1

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
jdubjdub
  • 613
  • 7
  • 21
Stéphane Appercel
  • 1,427
  • 2
  • 13
  • 21

1 Answers1

0

I see you've already opened an enhancement on the JSON-B repository, but I still wanted to document an answer here.

No, this is not possible with JSON-B 1.0, but I think it is a good idea and is an enhancement that should be considered for a future version of JSON-B.

Andy Guibert
  • 41,446
  • 8
  • 38
  • 61