Skip to content

Commit

Permalink
fix fastjson 1.x jsonpath compatible api return fastjson 2 JSONArray,…
Browse files Browse the repository at this point in the history
… for issue #2520
  • Loading branch information
wenshao committed May 7, 2024
1 parent 894ad03 commit 3466474
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,11 @@ public static Object extract(String json, String path) {
com.alibaba.fastjson2.JSONPath jsonPath = com.alibaba.fastjson2.JSONPath.of(path);
JSONReader.Context context = JSON.createReadContext(JSON.DEFAULT_PARSER_FEATURE);
JSONReader jsonReader = JSONReader.of(json, context);
return jsonPath.extract(jsonReader);
Object result = jsonPath.extract(jsonReader);
if (result instanceof com.alibaba.fastjson2.JSONArray) {
result = new com.alibaba.fastjson.JSONArray((com.alibaba.fastjson2.JSONArray) result);
}
return result;
}

public static boolean remove(Object root, String path) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package com.alibaba.fastjson.v2issues;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONPath;
import org.junit.jupiter.api.Test;

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

public class Issue2520 {
@Test
public void test() {
String testJson2 = "{\"result\":[{\"puid\":\"21025318\"},{\"puid\":\"21482682\"},{\"puid\":\"21025345\"}],\"state\":0}";
JSONArray result2 = (JSONArray) JSONPath.extract(testJson2, "$.result[0,2].puid");
assertNotNull(result2);
assertEquals("[\"21025318\",\"21025345\"]", result2.toJSONString());
}
}

0 comments on commit 3466474

Please sign in to comment.