TransWikia.com

Getting values(real value) from dynamic json object according to database records(place holders) and replace placeholders with real value

Stack Overflow Asked by HashanR on November 10, 2021

In this code section I need to get values from dynamic json object according to database record. I’ve two tables on database called notification and placeholders many to many relationship and notification can contain dynamic number of placeholders and one service will send json post request to this services so that replace places holders with real value but since this service doesn’t know about what are the number of dynamic placeholders real value should get from dynamic json array but json object contain notification id and using notification id I can get notification object and corresponding placeholders then I can get the real values from json object.

Here is dynamic json object.

{  
    "messageId":9,
    "msisdn":"94763703355",
    "<PACKNAME>":"Youtube",
    "<PACKTYPE>":"Social Media",
   
}

Here is a notification message related to messageId : 9

"You have succuessfully subscribe to <PACKNAME> and it will be <PACKTYPE> package"

This should be output :

"You have succuessfully subscribed to Youtube and it will be Social
Media package"

All placeholders should be replaced with relevant values but I’m unable to get expected output

@Service
public class NotificationServiceImpl implements NotificationService{

@Autowired
RestTemplate restTemplate;

@Autowired
NotificationRepository notificationRepository;

@Override
public void getdata(String dynamicJson) throws IOException {


    // create object mapper instance
    ObjectMapper mapper = new ObjectMapper();


    // convert JSON string to Java Object
    DynamicJson dynamicJson1 = mapper.readValue(dynamicJson, DynamicJson.class);

    // print user object
    //System.out.println(dynamicJson1);
    int id = dynamicJson1.getMessageId();

    Optional<Notification> notification = notificationRepository.findById(id);

    List<PlaceHolder> placeHolders = notification.get().getPlaceHolders();


    Map<String, String> replacements = new HashMap<String, String>();
    placeHolders.forEach(i -> replacements.put(i.getValue(), dynamicJson1.getPlaceholders().get(i).toString()));

   String message = notification.get().getMessage();

    StringBuilder result = new StringBuilder(message.length());
    String delimiters = "+-*/(),. ";
    StringTokenizer st = new StringTokenizer(message, delimiters, true);
    while (st.hasMoreTokens()) {
        String w = st.nextToken();
        if (replacements.containsKey(w)) {
            result.append(replacements.get(w));
        } else {
            result.append(w);
        }
    }
    System.out.println(result.toString());


}
}

Entity Class

public class DynamicJson {

@Override
public String toString() {
    return "DynamicJson{" +
            "messageId=" + messageId +
            ", msisdn='" + msisdn + ''' +
            ", placeholders=" + placeholders +
            '}';
}

public DynamicJson() {

}

public DynamicJson(int messageId, String msisdn, Map<String, Object> placeholders) {
    this.messageId = messageId;
    this.msisdn = msisdn;
    this.placeholders = placeholders;
}

public int getMessageId() {
    return messageId;
}

public void setMessageId(int messageId) {
    this.messageId = messageId;
}

public String getMsisdn() {
    return msisdn;
}

public void setMsisdn(String msisdn) {
    this.msisdn = msisdn;
}

public Map<String, Object> getPlaceholders() {
    return placeholders;
}

@JsonAnySetter
public void setAddress(String key, Object value) {
    placeholders.put(key, value);
}

private int messageId;
private String msisdn;
private Map<String, Object> placeholders = new HashMap<>();

}

Controller

@Autowired
NotificationService notificationService;

@RequestMapping(value = "/", method = RequestMethod.POST,
        consumes = "application/json", produces = "application/json")
public void getObject(@RequestBody String dynamicJson) throws IOException {

    notificationService.getdata(dynamicJson);

}

This is what I get as output

You have succuessfully subscribed to Youtube and it will be <PACKTYPE> package

You have succuessfully subscribed to <PACKNAME> and it will be Social Media package

What I really need is

You have succuessfully subscribed to Youtube and it will be Social Media package

Placeholder and realValue element count is dynamic and 1 to n

2 Answers

I could fix issue what I did is I placed the string builder replacing code section out side the for loop and also use Hashmap to map placeholder and realValue.

 @Override
    public void getdata(String dynamicJson) throws IOException {


        // create object mapper instance
        ObjectMapper mapper = new ObjectMapper();


        // convert JSON string to Java Object
        DynamicJson dynamicJson1 = mapper.readValue(dynamicJson, DynamicJson.class);


        int id = dynamicJson1.getMessageId();


        Optional<Notification> notification = notificationRepository.findById(id);

        List<PlaceHolder> placeHolders = notification.get().getPlaceHolders();

        //Changed
        HashMap<String, String> hash_map = new HashMap<String, String>();


        String message = notification.get().getMessage();


        for (int i = 0; i < placeHolders.size(); i++) {


            String placeholder = placeHolders.get(i).getValue();
            String realValue = dynamicJson1.getPlaceholders().get(placeholder).toString();

            //Changed
            hash_map.put(placeholder, realValue);

        }

        //////////////////////////////////////////////////////////////////////////////////

        StringBuilder result = new StringBuilder(message.length());
        String delimiters = "+-*/(),. ";
        StringTokenizer st = new StringTokenizer(message, delimiters, true);
        while (st.hasMoreTokens()) {
            String w = st.nextToken();
            if (hash_map.containsKey(w)) {
                result.append(hash_map.get(w));
            } else {
                result.append(w);
            }
        }


        System.out.println(result.toString());
    }

}

Answered by HashanR on November 10, 2021

It is your outer for loop. You loop over your placeholders. You should put your placeholders in a Map with the value being the realValue. Something like this:

Map<String, String> replacements = new HashMap<String, String>();
placeHolders.forEach(i -> replacements.put(i, dynamicJson1.getPlaceholders().get(i).toString()));
            
String sentence = "You have succuessfully subscribe to <PACKNAME> and it will be <PACKTYPE> package";
            
StringBuilder result = new StringBuilder(sentence.length());
String delimiters = "+-*/(),. ";
StringTokenizer st = new StringTokenizer(sentence, delimiters, true);
while (st.hasMoreTokens()) {
   String w = st.nextToken();
   if (replacements.containsKey(w)) {
      result.append(replacements.get(w));
   } else {
      result.append(w);
   }
}
System.out.println(result.toString());

Edit: here is the population of the map without using lambda:

for(String placeHolder: placeHolders) {
    replacements.put(placeHolder, dynamicJson1.getPlaceholders().get(placeHolder).toString()))
}

Answered by jnorman on November 10, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP