3 回答

TA貢獻2016條經驗 獲得超9個贊
這對我有用:
JSONArray jsonArray = (JSONArray)jsonObj.get("data"); JSONObject jsonObject = ((JSONObject)(jsonArray).get(0)); jsonObject.put("name", "abc"); System.out.println(jsonObj.toJSONString());

TA貢獻1796條經驗 獲得超10個贊
有時您可能會遇到以靈活的方式完美替換某些值的情況。所以我想展示這個使用json-path依賴項的附加方法。
指定路徑集合來替換真實數據,例如:
import static com.google.common.collect.Lists.newArrayList;
...
private static final List<String> PATHS_TO_REPLACE = newArrayList(
"$.email",
"$.colleagues.[*].email",
"$.other.required.pathmask"
);
最重要的代碼部分:
public String maskSensitiveData(String asJson) {
DocumentContext parsed = JsonPath.parse(asJson);
PATHS_TO_REPLACE.forEach(path -> parsed.set(path, "***starred***"));
return parsed.jsonString();
}
為了避免com.jayway.jsonpath.PathNotFoundException如果您確定必須抑制它們,您可以使用特殊配置:
private static final Configuration CONFIGURATION = Configuration
.builder()
.options(Option.SUPPRESS_EXCEPTIONS)
.build();
并parsed應以更新的方式提供文件:
DocumentContext parsed = JsonPath.using(CONFIGURATION).parse(asJson);
要使用代碼,我建議嘗試為相應的服務準備測試。
聚苯乙烯
如果您想以動態方式計算星星以設置值(或僅隱藏部分數據),也可以處理。為了使數據數組保持簡單,請注意map同一對象的方法。相應的示例也添加到服務中:
public String flexibleMaskingSensitiveData(String asJson) {
DocumentContext parsed = JsonPath.using(CONFIGURATION).parse(asJson);
PATHS_TO_REPLACE.forEach(path -> parsed.map(path,
(currentValue, conf) -> starringCurrentValue(currentValue)));
return parsed.jsonString();
}
private Object starringCurrentValue(Object currentValue) {
return ofNullable(currentValue)
.filter(String.class::isInstance)
.map(String.class::cast)
.map(String::length)
.map(times -> StringUtils.repeat('*', times))
.orElse("");
}
添加回答
舉報