Home > Back-end >  Create a new Json file then append other Json files to it
Create a new Json file then append other Json files to it

Time:10-27

Need to create a new json file (combined.json) then append multiple json files (json1 and json2) to combined.json.

Example:

Json 1 - previously created json file

[  
    {  
        "name":"John",
        "city":"Berlin",
        "cars":[  
            "audi",
            "bmw"
        ],
        "job":"Teacher"
    }
]

Json2 - previously created json file

[  
    {  
        "name":"Mark",
        "city":"Oslo",
        "cars":[  
            "VW",
            "Toyata"
        ],
        "job":"Doctor"
    }
]

Final product:

Combined.json - currenlty created json file

[  
    {  
        "name":"John",
        "city":"Berlin",
        "cars":[  
            "audi",
            "bmw"
        ],
        "job":"Teacher"
    },
    {  
        "name":"Mark",
        "city":"Oslo",
        "cars":[  
            "VW",
            "Toyata"
        ],
        "job":"Doctor"
    }
]

CodePudding user response:

    Gson gson = new com.google.gson.Gson();
    JSONArray combined = gson.fromJson(json1, JSONArray.class);
    combined.addAll(gson.fromJson(json2, JSONArray.class));
    // verify by looking on the value of: combined.toJSONString()
  • Related