VariableSubstitutor { public static String replace(String original, String valueP, String valueC) { if (original == null) { return null; } int pos = original.indexOf('%'); if (pos == -1) { return original; } String p = valueP == null ? "" : valueP; String c = valueC == null ? "" : valueC; StringBuilder result = new StringBuilder(original.length() + c.length() + p.length()); result.append(original, 0, pos); boolean isVariable = false; for ( ; pos < original.length(); pos++) { char current = original.charAt(pos); if (! isVariable) { if (current == '%') { isVariable = true; } else { result.append(current); } continue; } isVariable = false; switch (current) { case 'p': result.append(p); break; case 'c': result.append(c); break; case '%': result.append('%'); break; default: } } return result.toString(); } private  VariableSubstitutor(); static String replace(String original, String valueP, String valueC); static void replace(JsonArray json, String valueP, String valueC); static void replace(JsonObject json, String valueP, String valueC);  }
@Test void jsonArray() { JsonArray jsonArray = new JsonArray() .add("a %p") .add(new JsonObject().put("key", "b %c").put("key2", new JsonArray().add("b2 %p"))) .add("c %c") .add(new JsonArray().add("d %p")) .add(6) .add("e %p"); VariableSubstitutor.replace(jsonArray, "1234", "8.8.8.8"); assertThat(jsonArray).isEqualTo(new JsonArray() .add("a 1234") .add(new JsonObject().put("key", "b 8.8.8.8").put("key2", new JsonArray().add("b2 1234"))) .add("c 8.8.8.8") .add(new JsonArray().add("d 1234")) .add(6) .add("e 1234")); }
@Test void jsonObject() { JsonObject jsonObject = new JsonObject() .put("a %p", "a %p") .put("b %p", new JsonArray().add("b %c").add(new JsonObject().put("key", "b2 %p"))) .put("c %p", "c %p") .put("d %c", new JsonObject().put("key", "b %c")) .put("e %c", 6) .put("f %p", "f %p"); VariableSubstitutor.replace(jsonObject, "1234", "8.8.8.8"); assertThat(jsonObject).isEqualTo(new JsonObject() .put("a %p", "a 1234") .put("b %p", new JsonArray().add("b 8.8.8.8").add(new JsonObject().put("key", "b2 1234"))) .put("c %p", "c 1234") .put("d %c", new JsonObject().put("key", "b 8.8.8.8")) .put("e %c", 6) .put("f %p", "f 1234")); }