使用Java将三个json对象合并为一个

时间:2018-07-06 10:43:32

标签: java json ejb-3.0

我有这三个json对象:

object = [{name: "Mary", car: "Fiat"}];
owner= [{firstName: "Mack", lastName: "jack"},{firstName: "Steve", lastName: 
"martin"}];
children= [{firstName: "toto", lastName: "jack"},{firstName: "titi", lastName: 
"martin"}];

我正在使用JAVA,我想做的是将三个对象合并为一个对象:

[{"name": "Mary", "car": "Fiat",
"owner":[{"firstName": "Mack", "lastName": "jack"},{"firstName": 
"Steve","lastName": "martin"}],
"children":[{"firstName": "toto", "lastName": "jack"},{"firstName": "titi", 
"lastName": "martin"}]
}]

请帮忙!

2 个答案:

答案 0 :(得分:0)

您需要读取json文件并使用新的JSON结构中的更改创建一个新文件,我假设您已经知道如何从JSON文件中提取数据,并且我将在此处留下此代码示例以展示如何出于您的目的使用JSON.Arrays。

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

public class jsonClass {

public static void main(String[] args) {

    JSONObject jsonObject = new JSONObject();

    JSONArray jsonArray1 = new JSONArray();
    JSONObject jsonTempObject1 = new JSONObject();
    jsonTempObject1.put("name","Mary");
    jsonTempObject1.put("car","Fiat");
    jsonArray1.add(jsonTempObject1);

    JSONArray jsonArray2 = new JSONArray();
    JSONObject jsonTempObject2 = new JSONObject();
    jsonTempObject2.put("firstName","Mack");
    jsonTempObject2.put("lastName","Jack");
    jsonArray2.add(jsonTempObject2);

    jsonObject.put("object", jsonArray1);       
    jsonObject.put("owner", jsonArray2);

    System.out.println(jsonObject.toString());
    }
}

您将得到以下结果:

{
"owner":[{"firstName":"Mack","lastName":"Jack"}],
"object":[{"car":"Fiat","name":"Mary"}]
}

答案 1 :(得分:0)

使用以下代码

JSONObject Obj1 = (JSONObject) jso1.get("Object1");
JSONObject Obj2 = (JSONObject) jso2.get("Object2");
JSONObject combined = new JSONObject();
combined.put("Object1", Obj1);
combined.put("Object2", Obj2)