json-merge
A light weight library to merge two json objects into a single json object.
Overview
This library merges two json of any nested level into a single json following below logic.
-
When keys are different, both keys with there values will be copied at same level.
-
When keys are same at some level, following table denotes what value will be used.
Src / Target JSON Value JSON Array JSON Object JSON Value1 Src Src Src JSON Array Src2 Merge Src JSON Object Src Src Merge3 1 Json Value denotes boolean, number or string value in json.
2 Src denotesSrc
value will be copied.
3 Merge denotes bothSrc
andTarget
values will be merged.
Maven Artifact
To use this library add below to your dependencies in pom.xml
.
<dependency>
<groupId>com.github.hemantsonu20</groupId>
<artifactId>json-merge</artifactId>
<version>1.0.2</version>
</dependency>
Usage
This library exposes below method. It accepts source and target json and returns the merged json.
public static String merge(String srcJsonStr, String targetJsonStr);
Method Usage
String srcJsonStr = "{\"name\":\"json-merge\"}";
String targetJsonStr = "{\"age\":18}";
String output = JsonMerge.merge(srcJsonStr, targetJsonStr);
// {"name":"json-merge","age":18}
Examples
Example 1
Source Json
{
"name": "json-merge-src"
}
Target Json
{
"name": "json-merge-target"
}
Output
{
"name": "json-merge-src"
}
Example 2
Source Json
{
"level1": {
"key1": "SrcValue1"
}
}
Target Json
{
"level1": {
"key1": "targetValue1",
"level2": {
"key2": "value2"
}
}
}
Output Json
{
"level1": {
"key1": "SrcValue1",
"level2": {
"key2": "value2"
}
}
}
For more examples see, test json files.
Each test json file contains a json array of three json objects, first is src, second is target and third is output json.
Documentation
- Javadoc Releases are available at javadoc.io. (See javadoc badge above)
- Javadoc for latest code available via github pages here.