替换字符串中的“环境变量”,其中的值存储在 JSON 对象中 (爪哇)

问题描述

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

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 对象的创建。

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

解决方法

    //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
,

这就是 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,adipisci velit..