如何将数据附加到Gson JsonObject中的属性?

时间:2018-05-22 20:50:41

标签: java json gson

我有一个程序可以在json中返回资产的元数据。示例代码:

com.google.gson.JsonObject assetMetadataJson = new JsonObject();
assetMetadataJson.addProperty(asset.getName(), new Gson().toJson(asset.getMetadata()));

上述assetMetadataJson的示例输出为:

 {"icons8-java-50.png":"{\"dc:description\":[\"desc\"],\"dc:format\":\"image/png\"}"}

我们需要向同一个assetMetadataJson对象的属性添加更多详细信息。而且我们有另一个json字符串。像这样:

{"jcr:primaryType":"dam:Asset","jcr:isCheckedOut":true}

我们如何将上面两个json字符串注入/组合成一个,这样输出就像:

 {"icons8-java-50.png":"{\"dc:description\":[\"desc\"],\"dc:format\":\"image/png\"}","jcr:primaryType":"dam:Asset","jcr:isCheckedOut":true}

1 个答案:

答案 0 :(得分:0)

好吧,如果你有JsonElement个对象,那就很容易了:

private static JsonObject merge(final JsonObject jsonObject1, final JsonObject jsonObject2) {
    final JsonObject merged = new JsonObject();
    mergeInto(merged, jsonObject1);
    mergeInto(merged, jsonObject2);
    return merged;
}

private static void mergeInto(final JsonObject destination, final JsonObject source) {
    for ( final Map.Entry<String, JsonElement> e : source.entrySet() ) {
        destination.add(e.getKey(), e.getValue());
    }
}

或者在Java 8 Stream API中:

private static JsonObject merge(final JsonObject jsonObject1, final JsonObject jsonObject2) {
    return Stream.concat(jsonObject1.entrySet().stream(), jsonObject2.entrySet().stream())
            .collect(toJsonObject());
}

private static Collector<Map.Entry<String, JsonElement>, ?, JsonObject> toJsonObject() {
    return Collector.of(
            JsonObject::new,
            (jsonObject, e) -> jsonObject.add(e.getKey(), e.getValue()),
            (jsonObject1, jsonObject2) -> {
                for ( final Map.Entry<String, JsonElement> e : jsonObject2.entrySet() ) {
                    jsonObject1.add(e.getKey(), e.getValue());
                }
                return jsonObject1;
            },
            Function.identity()
    );
}