Skip to content

Commit f642994

Browse files
committed
jsonpath support new api reserve
1 parent 3fa45a4 commit f642994

File tree

3 files changed

+30
-4
lines changed

3 files changed

+30
-4
lines changed

pom.xml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
<modelVersion>4.0.0</modelVersion>
55
<groupId>com.alibaba</groupId>
66
<artifactId>fastjson</artifactId>
7-
<version>1.2.59_preview_02</version>
7+
<version>1.2.59_preview_05</version>
88

99
<packaging>jar</packaging>
1010
<name>fastjson</name>

src/main/java/com/alibaba/fastjson/JSONPath.java

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3864,7 +3864,25 @@ public String toJSONString() {
38643864
return JSON.toJSONString(path);
38653865
}
38663866

3867-
public static Object reserve(Object object, String... paths) {
3867+
public static Object reserveToArray(Object object, String... paths) {
3868+
JSONArray reserved = new JSONArray();
3869+
3870+
if (paths == null || paths.length == 0) {
3871+
return reserved;
3872+
}
3873+
3874+
for (String item : paths) {
3875+
JSONPath path = JSONPath.compile(item);
3876+
path.init();
3877+
3878+
Object value = path.eval(object);
3879+
reserved.add(value);
3880+
}
3881+
3882+
return reserved;
3883+
}
3884+
3885+
public static Object reserveToObject(Object object, String... paths) {
38683886
if (paths == null || paths.length == 0) {
38693887
return object;
38703888
}

src/test/java/com/alibaba/json/bvt/path/JSONPath_reverse_test.java

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,15 @@ public class JSONPath_reverse_test extends TestCase
1010
public void test_reserve() throws Exception {
1111
JSONObject object = JSON.parseObject("{\"id\":1001,\"name\":\"ljw\",\"age\":50}");
1212

13-
assertEquals("{\"id\":1001,\"name\":\"ljw\"}", JSONPath.reserve(object, "id", "name").toString());
14-
assertEquals("{\"name\":\"ljw\",\"id\":1001}", JSONPath.reserve(object, "name", "id").toString());
13+
assertEquals("[1001,\"ljw\"]", JSONPath.reserveToArray(object, "id", "name").toString());
14+
assertEquals("[\"ljw\",1001]", JSONPath.reserveToArray(object, "name", "id").toString());
15+
assertEquals("[\"ljw\",[\"ljw\",1001,50]]", JSONPath.reserveToArray(object, "name", "*").toString());
16+
}
17+
18+
public void test_reserve2() throws Exception {
19+
JSONObject object = JSON.parseObject("{\"id\":1001,\"name\":\"ljw\",\"age\":50}");
20+
21+
assertEquals("{\"id\":1001,\"name\":\"ljw\"}", JSONPath.reserveToObject(object, "id", "name").toString());
22+
assertEquals("{\"name\":\"ljw\",\"id\":1001}", JSONPath.reserveToObject(object, "name", "id").toString());
1523
}
1624
}

0 commit comments

Comments
 (0)