根据数据库记录(占位符)从动态json对象中获取值(实值),并用实值替换占位符



在这段代码中,我需要根据数据库记录从动态json对象中获取值。我在数据库上有两个表,名为notification和占位符多对多关系,notification可以包含占位符的动态数量,一个服务将向该服务发送json post请求,以便用实际值替换占位符,但由于该服务不知道实际值应该从动态json数组中获得的动态占位符数量,而是json对象包含通知id,使用通知id我可以获得通知对象和相应的占位符,然后我可以从json对象中获得实际值。

这里是动态json对象。

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

这是一条与messageId:9 相关的通知消息

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

应输出:

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

所有占位符都应该替换为相关值,但我无法获得预期的输出

@服务公共类NotificationServiceImpl实现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());

}
}

实体类

公共类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<>();

}

控制器

@自动连线NotificationService NotificationService;

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

这就是我得到的输出

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

我真正需要的是

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

占位符和realValue元素计数是动态的,并且为1到n

它是您的外部for循环。你在占位符上循环。您应该将占位符放在Map中,其值为realValue。类似这样的东西:

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());

编辑:这是不使用lambda:的地图的总体情况

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

我可以解决这个问题,我所做的是将字符串生成器替换代码部分放在for循环之外,还使用Hashmap映射占位符和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());
    }
}