如何在Java中合并两个`JSONObject`?

时间:2017-04-19 04:04:12

标签: java json

我有JSONObject#1喜欢:

"data":{
    "data_0":{"name": "Name 0"},
    "data_1":{"name": "Name 1"}
}

JSONObject#2喜欢:

{"data_2":{"name": "Name 2"}}

如何合并这两个JSONObject以获得以下结果:

"data":{
    "data_0":{"name": "Name 0"},
    "data_1":{"name": "Name 1"},
    "data_2":{"name": "Name 2"}
}

1 个答案:

答案 0 :(得分:0)

我在maven中使用google gson库:

jQuery(document).ready(function() {
  jQuery(window).resize(function() {
    var myDiv = jQuery("#myDiv"),
        myChild = myDiv.find("> *:first-child");
    myDiv.animate({
      scrollLeft: (myChild.width() - myDiv.width()) / 2
    }, {
      duration: 0
    });
  });

  jQuery(window).resize();
});

试试这段代码:

<dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.0</version>
        </dependency>

打印:

public static void main(String[] args) {
        String json1 = "{\"data\":\r\n{" + "    \"data_0\":{\"name\": \"Name 0\"},\r\n"
                + "    \"data_1\":{\"name\": \"Name 1\"}\r\n" + "}}";
        String json2 = "{\"data_2\":{\"name\": \"Name 2\"}}\r\n" + "";
        Map firstObject = new Gson().fromJson(json1, HashMap.class);
        Map secondObject = new Gson().fromJson(json2, HashMap.class);

        firstObject.putAll(secondObject);

        String resultJson = new Gson().toJson(firstObject);
        System.out.println(resultJson);
    }