0

I am reading data from file and I need to replace the placeholders with the java Bean values.

I have tried the StrSubstitutor to map the values but it did not worked, might me my approach is not right and declaration of placeholders are right please suggest me the right way

Class Test{
    String firstName;
    Request request;
}
class Request {
    String requestNumber;
}
setValues(){
    String template ="Dear ${test.firstname},Your Request number is ${test.request.requestNumber}.";
    Test test= test;
    Map<String, String> valuesMap = new HashMap<>();
    valuesMap.put("test.firstname",test.getFirstName());
    valuesMap.put("test.request.requestNumber",test.getRequest().getRequestNumber());
    StrSubstitutor StrSubstitutor = new StrSubstitutor(valuesMap);
    String mailContent = StrSubstitutor.replace(template );
}

Output should be

Dear firstName,Your Request number is 1234567.

Butiri Dan
  • 1,759
  • 5
  • 12
  • 18
Rikki
  • 1
  • 3

1 Answers1

0

You can basically replace each key by the value

String template ="Dear ${test.firstname},Your Request number is ${test.request.requestNumber}.";
Test test = ...;

Map<String, String> valuesMap = new HashMap<>();
valuesMap.put("test.firstname",test.getFirstName());
valuesMap.put("test.request.requestNumber",test.getRequest().getRequestNumber());

for (Map.Entry<String, String> entry : map.entrySet()) {
    template = template.replace("${" + entry.getKey() + "}", entry.getValue());
}

Check this post for more answers

IQbrod
  • 2,060
  • 1
  • 6
  • 28
  • if i have 100 fields in the object then i have to put 100 times the keys into the valuesMap, i want a solution so that i don't need to put the 100 keys to my Map and directly i can replace the xPaths provided into the template with objects – Rikki Aug 21 '19 at 06:28