Skip to content

Commit

Permalink
bug fix for JSONPath.set if parent is null
Browse files Browse the repository at this point in the history
  • Loading branch information
wenshao committed Jun 7, 2022
1 parent f76612d commit a179caa
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
28 changes: 28 additions & 0 deletions core/src/main/java/com/alibaba/fastjson2/JSONPath.java
Original file line number Diff line number Diff line change
Expand Up @@ -3156,6 +3156,34 @@ public void set(Object root, Object value) {
}

segment.eval(context);
if (context.value == null && nextSegment != null) {
if (value == null) {
return;
}

Object parentObject;
if (i == 0) {
parentObject = root;
} else {
parentObject = context.parent.value;
}

Object emptyValue;
if (nextSegment instanceof IndexSegment) {
emptyValue = new JSONArray();
} else if (nextSegment instanceof NameSegment) {
emptyValue = new JSONObject();
} else {
return;
}
context.value = emptyValue;

if (parentObject instanceof Map && segment instanceof NameSegment) {
((Map) parentObject).put(((NameSegment) segment).name, emptyValue);
} else if (parentObject instanceof List && segment instanceof IndexSegment) {
((List) parentObject).set(((IndexSegment) segment).index, emptyValue);
}
}
}
context = new Context(this, context, segments.get(0), null, 0L);
context.root = root;
Expand Down
16 changes: 16 additions & 0 deletions core/src/test/java/com/alibaba/fastjson2/issues/Issue424.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
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 Issue424 {
@Test
public void test() {
JSONObject jsonObject = new JSONObject();
JSONPath.set(jsonObject, "a[0].b", 1);
assertEquals("{\"a\":[{\"b\":1}]}", jsonObject.toString());
}
}

0 comments on commit a179caa

Please sign in to comment.