Skip to content

Commit

Permalink
bug fix for two segment JSONPath set error, for issue #476
Browse files Browse the repository at this point in the history
  • Loading branch information
wenshao committed Jun 16, 2022
1 parent 7051809 commit 982cfcd
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 1 deletion.
16 changes: 15 additions & 1 deletion core/src/main/java/com/alibaba/fastjson2/JSONPath.java
Original file line number Diff line number Diff line change
Expand Up @@ -2936,7 +2936,21 @@ public void set(Object root, Object value) {
context0.root = root;
first.eval(context0);
if (context0.value == null) {
return;
Object emptyValue;
if (second instanceof IndexSegment) {
emptyValue = new JSONArray();
} else if (second instanceof NameSegment) {
emptyValue = new JSONObject();
} else {
return;
}

context0.value = emptyValue;
if (root instanceof Map && first instanceof NameSegment) {
((Map) root).put(((NameSegment) first).name, emptyValue);
} else if (root instanceof List && first instanceof IndexSegment) {
((List) root).set(((IndexSegment) first).index, emptyValue);
}
}

Context context1 = new Context(this, context0, second, null, 0);
Expand Down
17 changes: 17 additions & 0 deletions core/src/test/java/com/alibaba/fastjson2/issues/Issue476.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package com.alibaba.fastjson2.issues;

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

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

public class Issue476 {
@Test
public void test() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("c", "c");
JSONPath.set(jsonObject, "$.a.b", "123");
assertEquals("{\"c\":\"c\",\"a\":{\"b\":\"123\"}}", jsonObject.toJSONString());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import org.junit.jupiter.api.Test;

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

public class JSONPath_18 {
String str = "{ \"inputs\": {\n" +
Expand Down Expand Up @@ -48,4 +49,10 @@ public void test1() {
.toString()
);
}

@Test
public void test2() {
Object object = new Object();
assertSame(object, JSONPath.of("$").eval(object));
}
}

0 comments on commit 982cfcd

Please sign in to comment.