Skip to content

Commit

Permalink
fix JSONPath#set, for issue #842
Browse files Browse the repository at this point in the history
  • Loading branch information
wenshao committed Oct 29, 2022
1 parent d120ce9 commit 7ed8a94
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
5 changes: 5 additions & 0 deletions core/src/main/java/com/alibaba/fastjson2/JSONPath.java
Original file line number Diff line number Diff line change
Expand Up @@ -4814,6 +4814,11 @@ public void set(Context context, Object value) {
if (object instanceof java.util.List) {
List list = (List) object;
if (index >= 0) {
if (index > list.size()) {
for (int i = list.size(); i < index; ++i) {
list.add(null);
}
}
if (index < list.size()) {
list.set(index, value);
} else if (index <= list.size()) {
Expand Down
15 changes: 15 additions & 0 deletions core/src/test/java/com/alibaba/fastjson2/issues/Issue842.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.alibaba.fastjson2.issues;

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

Expand All @@ -25,4 +26,18 @@ public void test1() {
JSONPath.set(data, jsonPath, "设置成功");
assertEquals("{\"items\":[{\"data\":[\"设置成功\"]}]}", JSON.toJSONString(data));
}

@Test
public void test2() {
Map data = new LinkedHashMap<>();
JSONPath.set(data, "$.obj.5", "设置成功");
assertEquals("{\"obj\":[null,null,null,null,null,\"设置成功\"]}", JSONObject.toJSONString(data));
}

@Test
public void test3() {
Map data = new LinkedHashMap<>();
JSONPath.set(data, "$.obj.2.5", "设置成功");
assertEquals("{\"obj\":[null,null,[null,null,null,null,null,\"设置成功\"]]}", JSONObject.toJSONString(data));
}
}

0 comments on commit 7ed8a94

Please sign in to comment.