簡體   English   中英

將 json 對象與 java 合並

[英]Merge json objects with java

我有兩個 JSON 文件。 我想將它們組合成一個,使第二個文件具有更高的優先級。 那是:

  • 如果 1 具有屬性foo而 2 沒有屬性foo ,則 3 將具有屬性foo ,其值從 1 開始。
  • 如果 2 具有屬性foo而 1 沒有屬性foo ,則 3 將具有屬性foo ,其值來自 2。
  • 如果 1 和 2 都具有屬性foo ,則 3 將具有屬性foo ,其值來自 2。

我需要在 Java 中執行此操作。 The final JSON object will be deserialized to a Java object with Google Gson.

干得好:

Gson gson = new Gson();
//read both jsons
Map<String, Object> json1 = gson.fromJson("<json1>", Map.class);
Map<String, Object> json2 = gson.fromJson("<json2>", Map.class);
//create combined json with contents of first json
Map<String, Object> combined = new HashMap<>(json1);
//Add the contents of first json. It will overwrite the values of keys are 
//same. e.g. "foo" of json2 will take precedence if both json1 and json2 have "foo" 
combined.putAll(json2);
gson.toJson(combined);

要深度合並具有自定義優先級的 JSON 文件並返回為 Gson,您應該使用confectory-datamapper-gson httpsr/ githubconfector.com/wiki/Downvicload.

你可以這樣做:

Configuration<JsonObject> json1 = Configuration.<JsonObject>builder()
                .mapper(new GsonJsonObjectMapper())
                .source("classpath://file1.json")
                .precedence(9) // Higher priority
                .build();

Configuration<JsonObject> json2 = Configuration.<JsonObject>builder()
                .mapper(new GsonJsonObjectMapper())
                .source("classpath://file2.json")
                .precedence(1) // Lower priority
                .build();

JsonObject merged = json1.merge(json2).getBean();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM