Skip to content

Commit 4623187

Browse files
caimoQIURC
andauthored
fix JSONArray merge(Object)(#51) (#247)
Co-authored-by: QIURC <[email protected]>
1 parent 5efc9ab commit 4623187

File tree

2 files changed

+45
-1
lines changed

2 files changed

+45
-1
lines changed

json-smart/src/main/java/net/minidev/json/JSONObject.java

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -236,7 +236,9 @@ private static JSONObject merge(JSONObject o1, JSONObject o2, boolean overwrite)
236236

237237
protected static JSONArray merge(JSONArray o1, Object o2) {
238238
if (o2 == null) return o1;
239-
if (o1 instanceof JSONArray) return merge(o1, (JSONArray) o2);
239+
if (o2 instanceof JSONArray) {
240+
return merge(o1, (JSONArray) o2);
241+
}
240242
o1.add(o2);
241243
return o1;
242244
}

json-smart/src/test/java/net/minidev/json/test/JSONObjectTest.java

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,4 +189,46 @@ void mergeJsonObjectWithOverwriteSuccess() {
189189
jsonObject4.merge(jsonObject2, true);
190190
Assertions.assertEquals("{\"k2\":{\"k1\":\"v1\"}}", jsonObject4.toJSONString());
191191
}
192+
193+
@Test
194+
void mergeJsonArrayWithObjectSuccess() {
195+
JSONObject jsonObject1 = new JSONObject();
196+
jsonObject1.appendField("k1", "v1");
197+
198+
JSONArray jsonArray1 = new JSONArray();
199+
jsonArray1.add(jsonObject1);
200+
Assertions.assertEquals("[{\"k1\":\"v1\"}]", jsonArray1.toJSONString());
201+
202+
JSONObject jsonObject2 = new JSONObject();
203+
jsonObject2.appendField("k2", "v2");
204+
205+
/*
206+
test merge json object ( before fix issue #51, these will fail.
207+
throw java.lang.ClassCastException: class net.minidev.json.JSONObject cannot be cast to class net.minidev.json.JSONArray)
208+
*/
209+
jsonArray1.merge(jsonObject2);
210+
Assertions.assertEquals("[{\"k1\":\"v1\"},{\"k2\":\"v2\"}]", jsonArray1.toJSONString());
211+
212+
jsonArray1.merge("s1");
213+
Assertions.assertEquals("[{\"k1\":\"v1\"},{\"k2\":\"v2\"},\"s1\"]", jsonArray1.toJSONString());
214+
215+
jsonArray1.merge(1);
216+
Assertions.assertEquals(
217+
"[{\"k1\":\"v1\"},{\"k2\":\"v2\"},\"s1\",1]", jsonArray1.toJSONString());
218+
219+
jsonArray1.merge(true);
220+
Assertions.assertEquals(
221+
"[{\"k1\":\"v1\"},{\"k2\":\"v2\"},\"s1\",1,true]", jsonArray1.toJSONString());
222+
223+
// test merge json array
224+
JSONObject jsonObject3 = new JSONObject();
225+
jsonObject3.appendField("k3", "v3");
226+
JSONArray jsonArray2 = new JSONArray();
227+
jsonArray2.add(jsonObject3);
228+
229+
jsonArray1.merge(jsonArray2);
230+
Assertions.assertEquals(
231+
"[{\"k1\":\"v1\"},{\"k2\":\"v2\"},\"s1\",1,true,{\"k3\":\"v3\"}]",
232+
jsonArray1.toJSONString());
233+
}
192234
}

0 commit comments

Comments
 (0)