我正在尝试实现一个将 JSON-PATCH (RFC 6902) 应用于使用 JSON-B 注释的对象的函数。
我得出了以下解决方案:
/**
* 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
}
}
这种方法的问题在于过程中发生的序列化/反序列化的数量,更不用说实现不流畅。
我是否遗漏了 API 中的某些内容以简化此修补功能的实现,或者仅仅是 JSON-B 和 JSON 之间缺少一座桥梁,例如:
jsonb.toJsonStructure(object); // would return a JSON Processing JsonStructure