【问题标题】:Missing bridge between JSON-B and JSON APIs?JSON-B 和 JSON API 之间缺少桥梁?
【发布时间】:2018-01-10 18:50:28
【问题描述】:

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

【问题讨论】:

    标签: java json json-patch jsonb-api


    【解决方案1】:

    我看到你已经opened an enhancement on the JSON-B repository,但我仍然想在这里记录一个答案。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-12
      • 2011-08-26
      • 2013-03-24
      • 2011-08-17
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      相关资源
      最近更新 更多