2 回答

TA貢獻2065條經驗 獲得超14個贊
我不建議使用正則表達式,更好的選擇是使用庫來解析 json,刪除值,然后再次將其轉換為字符串。
JSONObject jsonObject = new JSONObject(input);
jsonObject.getJSONObject("expressions").remove("storyId");
String output = jsonObject.toString();
如果你真的想使用正則表達式,你可以使用以下
jsonString.replaceAll("(\\\"storyId\\\"|\\'storyId\\')\\s*:\\s*(\\\"[^\\\"]*\\\"|'[^\\\"]*')\\s*,?", "");
但只要確保 storyId 真的是一個字符串,否則這個正則表達式將不起作用。
編輯:更新了我的答案,如果你想要一個使用正則表達式刪除參數的函數,
void replaceAllKeys(String keyName, String jsonAsString) {
String pattern = String.format("(\\\"%s\\\"|\\'%s\\')\\s*:\\s*(\\\"[^\\\"]*\\\"|'[^\\\"]*')\\s*,?", keyName, keyName);
return jsonAsString.replaceAll(pattern, "");
}

TA貢獻1744條經驗 獲得超4個贊
首先,我假設您將獲取所有 json 對象,jsonObj
然后remove()
通過傳遞您的 json 鍵來調用,如下所示:
jsonObj.getAsJsonObject("expressions").remove("storyId");
添加回答
舉報