JSONPath增强,支持对Json字符串进行脱敏处理
davionchen opened this issue · comments
请描述您的需求或者改进建议
出于数据安全的考虑,需要对json字符串进行脱敏。
比如字符串
{
"students": [
{
"name": "a",
"mobile": "123"
}, {
"name": "b",
"mobile": "456"
}
],
"teacher": {
"name": "xyz",
"mobile": "456"
}
}
请描述你建议的实现方案
在不转化为JavaBean的情况下,需要使用JSONPath进行处理。
目标 输入inputPath = $..name,对所有name进行打码。
方案A:使用JSONPath.paths,获取所有的path。引入新方法public boolean hasChildPath(String childPath)确认是否属于inputPath,然后进行打码。
方案B:引入public String walk(path,pathCallback),支持遍历与修改。
2.0.3-SNAPSHOT版本中,你可以这样用:
public class JSONPathSetCallbackTest {
@Test
public void test() {
JSONObject object = JSONObject.of("id", 101);
JSONPath.setCallback(object, "$.id", o -> ((Integer) o).intValue() + 1);
assertEquals(102, object.getIntValue("id"));
}
@Test
public void test1() {
JSONObject object = JSONObject.of("id", 101);
JSONPath.setCallback(object, "$..id", o -> ((Integer) o).intValue() + 1);
assertEquals(102, object.getIntValue("id"));
}
@Test
public void test2() {
JSONObject object = JSONObject.of("item", JSONObject.of("id", 101));
JSONPath.setCallback(object, "$.item.id",
o -> ((Integer) o).intValue() + 1
);
assertEquals(102, object.getJSONObject("item").getIntValue("id"));
}
@Test
public void testBean0() {
Bean bean = new Bean();
bean.id = 101;
JSONPath.setCallback(bean, "$.id", o -> ((Integer) o).intValue() + 1);
assertEquals(102, bean.id);
}
public static class Bean {
public int id;
}
}
2.0.3 已经发布,请使用新版本 https://github.com/alibaba/fastjson2/releases/tag/2.0.3
谢谢。
目前已经做了测试。fastjson1的Fastjson1ValueFilter,fastjson2的Fastjson2JsonPath,jayway的JaywayJsonPath 对比
性能结果 :Fastjson1ValueFilter >Fastjson2Jsonpath. >JaywayJsonpath
测试字符串 :{"abc":"fasd","testList":[{"abc":"dfadf"}]}
脱敏结果:{"abc":"sha256@60d203f36c2f7d24077b2cd58e03d265df10d5c410d079ee4d1da4ffef8a1230","testList":[{"abc":"sha256@29d5013b028f96981c07198bde9ebb82493fb177dbfbab4d9c82637820c9ffe3"}]}
单位:毫秒
JsonPath:13个未命中,1个命中(abc)
案例 | Fastjson1ValueFilter | Fastjson2JsonPath | JaywayJsonPath |
---|---|---|---|
100w循环 | 2801 | 3145 | 8775 |
200w循环 | 4757 | 5852 | 16457 |
400w循环 | 8252 | 11484 | 30103 |
可以提供下testcase的代码么?我看是否能做进一步调优。FASTJSONv2也是支持ValueFilter的