Skip to content

Commit

Permalink
bug fix for JSONPath.set if exists, for issue #431
Browse files Browse the repository at this point in the history
  • Loading branch information
wenshao committed Jun 7, 2022
1 parent a179caa commit 02a156b
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 10 deletions.
11 changes: 1 addition & 10 deletions core/src/main/java/com/alibaba/fastjson2/JSONPath.java
Original file line number Diff line number Diff line change
Expand Up @@ -2252,16 +2252,7 @@ public boolean contains(Object root) {
public void set(Object rootObject, Object value) {
if (rootObject instanceof Map) {
Map map = (Map) rootObject;
Object origin = map.put(name, value);
if (origin != null) {
if (origin instanceof Collection) {
((Collection) origin).add(value);
map.put(name, value);
} else {
JSONArray array = JSONArray.of(origin, value);
map.put(name, array);
}
}
map.put(name, value);
return;
}
ObjectReaderProvider provider = getReaderContext().getProvider();
Expand Down
38 changes: 38 additions & 0 deletions core/src/test/java/com/alibaba/fastjson2/issues/Issue431.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package com.alibaba.fastjson2.issues;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONPath;
import com.alibaba.fastjson2.JSONReader;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class Issue431 {
@Test
public void test() {
String jsonStr = "{\"aaa\":\"a111\",\"bbb\":\"b11111\"}";
JSONObject jsonObject = JSON.parseObject(jsonStr);

String valueStr = "{\"ccc\":\"c111\",\"ddd\":\"d11111\"}";
JSONObject value = JSON.parseObject(valueStr);

JSONPath.set(jsonObject, "$.aaa", value);
assertEquals("{\"aaa\":{\"ccc\":\"c111\",\"ddd\":\"d11111\"},\"bbb\":\"b11111\"}", jsonObject.toString());
}

@Test
public void test1() {
JSONObject object = JSONObject.of("id", 123);
JSONPath path = JSONPath.of("$.id");

path.set(object, 101);
assertEquals(101, object.get("id"));

path.set(object, 102);
assertEquals(102, object.get("id"));

path.set(object, 103, JSONReader.Feature.DuplicateKeyValueAsArray);
assertEquals("[102,103]", object.get("id").toString());
}
}

0 comments on commit 02a156b

Please sign in to comment.