This commit is contained in:
Looly 2020-11-29 00:46:37 +08:00
parent 07c2870685
commit 9857ac4484
2 changed files with 11 additions and 5 deletions

View File

@ -420,7 +420,7 @@ public class JSONObject implements JSON, JSONGetter<String>, Map<String, Object>
} }
/** /**
* 积累值类似于put当key对应value已经存在时与value组成新的JSONArray. <br> * 积累值类似于set当key对应value已经存在时与value组成新的JSONArray. <br>
* 如果只有一个值此值就是value如果多个值则是添加到新的JSONArray中 * 如果只有一个值此值就是value如果多个值则是添加到新的JSONArray中
* *
* @param key * @param key
@ -432,11 +432,11 @@ public class JSONObject implements JSON, JSONGetter<String>, Map<String, Object>
InternalJSONUtil.testValidity(value); InternalJSONUtil.testValidity(value);
Object object = this.getObj(key); Object object = this.getObj(key);
if (object == null) { if (object == null) {
this.set(key, (value instanceof JSONArray) ? value : new JSONArray(this.config).set(value)); this.set(key, value);
} else if (object instanceof JSONArray) { } else if (object instanceof JSONArray) {
((JSONArray) object).set(value); ((JSONArray) object).set(value);
} else { } else {
this.set(key, new JSONArray(this.config).set(object).set(value)); this.set(key, JSONUtil.createArray(this.config).set(object).set(value));
} }
return this; return this;
} }

View File

@ -538,7 +538,13 @@ public class JSONObjectTest {
@Test @Test
public void accumulateTest(){ public void accumulateTest(){
final JSONObject accumulate = JSONUtil.createObj().accumulate("key1", "value1"); final JSONObject jsonObject = JSONUtil.createObj().accumulate("key1", "value1");
Assert.assertEquals("{\"key1\":[\"value1\"]}", accumulate.toString()); Assert.assertEquals("{\"key1\":\"value1\"}", jsonObject.toString());
jsonObject.accumulate("key1", "value2");
Assert.assertEquals("{\"key1\":[\"value1\",\"value2\"]}", jsonObject.toString());
jsonObject.accumulate("key1", "value3");
Assert.assertEquals("{\"key1\":[\"value1\",\"value2\",\"value3\"]}", jsonObject.toString());
} }
} }