From a179caa1b271a1d3db667b5fad5e49dd1789a697 Mon Sep 17 00:00:00 2001 From: "shaojin.wensj" Date: Wed, 8 Jun 2022 04:02:54 +0800 Subject: [PATCH] bug fix for JSONPath.set if parent is null --- .../java/com/alibaba/fastjson2/JSONPath.java | 28 +++++++++++++++++++ .../alibaba/fastjson2/issues/Issue424.java | 16 +++++++++++ 2 files changed, 44 insertions(+) create mode 100644 core/src/test/java/com/alibaba/fastjson2/issues/Issue424.java diff --git a/core/src/main/java/com/alibaba/fastjson2/JSONPath.java b/core/src/main/java/com/alibaba/fastjson2/JSONPath.java index b97546186f..b2c33f34b5 100644 --- a/core/src/main/java/com/alibaba/fastjson2/JSONPath.java +++ b/core/src/main/java/com/alibaba/fastjson2/JSONPath.java @@ -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; diff --git a/core/src/test/java/com/alibaba/fastjson2/issues/Issue424.java b/core/src/test/java/com/alibaba/fastjson2/issues/Issue424.java new file mode 100644 index 0000000000..a3c8ffe33c --- /dev/null +++ b/core/src/test/java/com/alibaba/fastjson2/issues/Issue424.java @@ -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()); + } +}