@@ -164,10 +164,60 @@ public JsonElement put(String key, Boolean value) {
164
164
return put (key , new JsonElement (value ));
165
165
}
166
166
167
+ /**
168
+ * Puts {@link JsonElement} of type {@link JsonElementType#NULL} into this {@link JsonObject}.
169
+ *
170
+ * @param key the key to put a NULL JSON value into
171
+ * @return the previous {@link JsonElement} associated with this key
172
+ */
167
173
public JsonElement putNull (String key ) {
168
174
return put (key , new JsonElement ());
169
175
}
170
176
177
+ /**
178
+ * Merges this {@link JsonObject} with another resulting in a new {@code JsonObject}.
179
+ * <ol>
180
+ * <li>If key in both and each value is an object then it will recursively merge and add to result</li>
181
+ * <li>If key in both and each value is not an object, value from the right is added to the result</li>
182
+ * <li>If key in this only, then this value is added to result</li>
183
+ * <li>If key in other only, then other value is added to result</li>
184
+ * </ol>
185
+ * This does not create a deep copy of nested arrays and objects.
186
+ *
187
+ * @param other the object to merge with
188
+ * @return a new {@code JsonObject} with merged properties
189
+ */
190
+ public JsonObject merge (JsonObject other ) {
191
+ JsonObject result = new JsonObject ();
192
+
193
+ forEach ((key , value ) -> {
194
+ var otherValue = other .get (key );
195
+
196
+ // add in any unique keys from this object
197
+ if (otherValue == null ) {
198
+ result .put (key , value );
199
+ } else {
200
+ // nested merge if value in both is an object
201
+ if (value .getType () == JsonElementType .JSON_OBJECT && otherValue .getType () == JsonElementType .JSON_OBJECT ) {
202
+ result .put (key , value .asObject ().merge (otherValue .asObject ()));
203
+ } else {
204
+ result .put (key , otherValue );
205
+ }
206
+ }
207
+ });
208
+
209
+ // add in any unique keys from the other object
210
+ other .forEach ((key , value ) -> {
211
+ var thisValue = this .get (key );
212
+
213
+ if (thisValue == null ) {
214
+ result .put (key , value );
215
+ }
216
+ });
217
+
218
+ return result ;
219
+ }
220
+
171
221
@ Override
172
222
public String toString () {
173
223
return toString (0 );
@@ -184,5 +234,6 @@ public String toString(int spaces) {
184
234
185
235
solaJsonSerializer .getConfig ().setSpaces (spaces );
186
236
187
- return solaJsonSerializer .serialize (this ); }
237
+ return solaJsonSerializer .serialize (this );
238
+ }
188
239
}
0 commit comments