我正在尝试实现一个函数,该函数将JSON-PATCH (RFC6902)应用于使用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发布于 2018-12-11 00:43:39
我看到你已经opened an enhancement on the JSON-B repository了,但我还是想在这里记录一个答案。
不,这在JSON-B 1.0中是不可能的,但我认为这是一个好主意,应该在JSON-B的未来版本中考虑这一增强。
https://stackoverflow.com/questions/48194222
复制相似问题