Quantcast
Channel: Crunchify
Viewing all articles
Browse latest Browse all 1037

How to Merge/Concat Multiple JSONObjects in Java? Best way to Combine two JSONObjects

$
0
0

Merge Two JSON Objects Utility by Crunchify

In Java – What is the best way to combine / merge multiple JSONObjects? JSONObject is an unordered collection of name/value pairs and widely used in Java Enterprise applications for data transfer between client / server over REST interface.

You need below Maven Dependency for JSONObject.

<dependency>
	<groupId>org.json</groupId>
	<artifactId>json</artifactId>
	<version>20140107</version>
</dependency>

Sometimes it will be great to have handy utility ready which combines two or multiple JSONObjects. Here is simple Java example which shows the same.

package crunchify.com.tutorials;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * @author Crunchify.com
 *
 */
public class CrunhifyMergeJSONObjects {

	public static void main(String[] args) {
		JSONObject json1 = new JSONObject();
		JSONObject json2 = new JSONObject();

		json1.put("Crunchify", "Java Company");
		json1.put("Google", "Search Company");
		json1.put("Yahoo", "Web Company");

		json2.put("Facebook", "Social Network Company");
		json2.put("Twitter", "Another Social Company");
		json2.put("Linkedin", "Professional Network Company");

		System.out.println("json1: " + json1);
		System.out.println("json2: " + json2);

		JSONObject mergedJSON = mergeJSONObjects(json1, json2);
		System.out.println("\nmergedJSON: " + mergedJSON);
	}

	public static JSONObject mergeJSONObjects(JSONObject json1, JSONObject json2) {
		JSONObject mergedJSON = new JSONObject();
		try {
			mergedJSON = new JSONObject(json1, JSONObject.getNames(json1));
			for (String crunchifyKey : JSONObject.getNames(json2)) {
				mergedJSON.put(crunchifyKey, json2.get(crunchifyKey));
			}

		} catch (JSONException e) {
			throw new RuntimeException("JSON Exception" + e);
		}
		return mergedJSON;
	}
}

Result:

json1: 
{
    "Crunchify": "Java Company",
    "Yahoo": "Web Company",
    "Google": "Search Company"
}
json2: 
{
    "Linkedin": "Professional Network Company",
    "Facebook": "Social Network Company",
    "Twitter": "Another Social Company"
}

mergedJSON: 
{
    "Crunchify": "Java Company",
    "Linkedin": "Professional Network Company",
    "Yahoo": "Web Company",
    "Facebook": "Social Network Company",
    "Google": "Search Company",
    "Twitter": "Another Social Company"
}

Next I’ll write example on ObjectMapper which PrettyPrint JSON object in Eclipse Console.

Have a suggestion on article? Please chime in and share it as a comment.

The post How to Merge/Concat Multiple JSONObjects in Java? Best way to Combine two JSONObjects appeared first on Crunchify.

Author: App Shah

Crunchify, LLC Logo


Viewing all articles
Browse latest Browse all 1037

Trending Articles