缺少JSON-B和JSON API之间的桥梁?

时间:2018-01-10 18:50:29

标签: java json json-patch jsonb-api

我正在尝试实现一个将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

1 个答案:

答案 0 :(得分:0)

我看到您已经opened an enhancement on the JSON-B repository,但是我仍然想在此处记录答案。

不,这在JSON-B 1.0中是不可能的,但是我认为这是个好主意,并且是将来的JSON-B版本应考虑的增强功能。