【问题标题】:Replacing "Environmental Variables" in a String which values are stored inside a JSON object. (JAVA)替换存储在 JSON 对象中的字符串中的“环境变量”。 (JAVA)
【发布时间】:2021-08-05 16:43:57
【问题描述】:

假设有一个这样的字符串:

String str = "Lorem Ipsum Neque porro <userEnv.value1> quisquam est qui <userEnv.value2> dolorem
              ipsum quia <userEnv.value2> dolor sit amet, consectetur, adipisci velit..";

我有一个这样的 JSON:

"userEnv":{
     "value1":"important info",
     "value2":"other important info",
     "value3":"even other important info"
}

我需要找到一种巧妙的方法来替换存储在 JSON userEnv 中的字符串中的每个值。

我考虑做如下事情:

        JsonObject jsonObject = Json.createObject();
        jsonObject.put(
            "userEnv",
            "\"value1\":\"important info\",\"value2\":\"other important info\",\"value3\":\"even other important info\");
        
        Pattern pattern = Pattern.compile(".*[<](.*)[>].*");
        Matcher matcher = pattern.matcher(str);

        int groupPointer = 0;
        while (matcher.find()){

            if (jsonObject.get(matcher.group(groupPointer))!=null){
                str = str.replaceAll(
                           ".*<"+matcher.group(groupPointer)+">.*",
                           jsonObject.get(matcher.group(groupPointer))
                 );
            }
        }

但这不起作用,没有找到任何组,也许我的正则表达式表达不好。

另外,我不确定 JSON 对象的创建。

也许我应该明天发这个,而不是今晚太累了。

【问题讨论】:

    标签: java json string replace matcher


    【解决方案1】:
        //using JSONObject from org.json library you could do the following
        JSONObject jsonObject = new JSONObject("{\"userEnv\":{\n" +
                "     \"value1\":\"important info\",\n" +
                "     \"value2\":\"other important info\",\n" +
                "     \"value3\":\"even other important info\"\n" +
                "}}");
        String str = "Lorem Ipsum Neque porro <userEnv.value1> quisquam est qui <userEnv.value2> dolorem " +
                "ipsum quia <userEnv.value2> dolor sit amet, consectetur, adipisci velit..";
        for (String outerKey : jsonObject.keySet()) {
            JSONObject outerKeyValue = jsonObject.getJSONObject(outerKey);
            for (String innerKey : outerKeyValue.keySet()) {
                String innerKeyValue = outerKeyValue.getString(innerKey);
                str = str.replace("<" + outerKey + "." + innerKey + ">", innerKeyValue);
            }
        }
        //here str has replaced all placeHolders of type <outerKey.innerKey> for which there were values in the json
    

    【讨论】:

    • 感谢您的回答,我意识到我需要事先展平。我使用了另一种方法,因为 Json 树比 2 个键更深(或更高)。谢谢!
    【解决方案2】:

    这就是StringSubstitutor of Apache Commons Text 的用途:

    Gson gson = new Gson();
    JsonObject json = gson.fromJson(jsonStr, JsonObject.class);
    Map<String, String> map = gson.fromJson(json.getAsJsonObject("userEnv"), new TypeToken<Map<String, String>>(){}.getType());
    
    Map<String, String> placeHolderToValue = map.entrySet().stream() // adding "userEnv."
            .collect(Collectors.toMap(key -> "userEnv." + key.getKey(), Map.Entry::getValue));
    
    StringSubstitutor sub = new StringSubstitutor(placeHolderToValue, "<", ">");
    String result = sub.replace(str);
    
    System.out.println(result);
    

    输出:

    Lorem Ipsum Neque porro important info quisquam est qui other important info dolorem
                  ipsum quia other important info dolor sit amet, consectetur, adipisci velit..
    

    【讨论】:

    • 感谢您的回答。我使用了 StringSubstitutor 并且工作得非常好。我也确实在我的问题中指定了 Json 树有点复杂,所以我需要先展平所有键。
    • 如果您发现答案有帮助,您可以点赞:)
    猜你喜欢
    • 2021-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-24
    相关资源
    最近更新 更多