mercredi 23 août 2023

set and get entity value dynamically through a function

Im trying to make a function that parses a jwt token and sets them in a model with getter setters dynamically. Function is called at the very bottom.

@Autowired
private ObjectMapper objectMapper;

public Object decryptRequest(ClientRequest request, Class<?> clazzToMap) throws Exception {
    String jwt = request.getEncryptedPayload().split(" ")[1];
    log.info("Removed Bearer: {}", jwt);
    String body = jwt.split("\\.")[1];
    log.info("Extracted body: {}", body);
    byte[] content = Base64.getUrlDecoder().decode(body);
    Object reqConverted = objectMapper.readValue(content, clazzToMap);

    log.info("Reading fields from: {}", clazzToMap.getName());
    log.info("Field value: {}", clazzToMap.getDeclaredFields()[0]);

    // Object obj = PaymentRequest.class.getConstructor(PaymentRequest.class).newInstance(reqConverted);

    Field[] fields = reqConverted.getClass().getDeclaredFields();
    log.info("Field length: {}", fields.length);
    for(Field field : fields) {
        field.setAccessible(true);
        log.info("{} : {}", field.getName(), ???);
    }
    
    return reqConverted;
}

@Getter
@Setter
public class PaymentRequest {
   private String accountNo;
   private String accountName;
   private String item;
   private String price;
}

//Function is called like this
PaymentRequest request = (PaymentRequest) cryptService.decryptRequest(cReq, PaymentRequest.class);

What's the best way to do it? I'm not able to figure out what the '???' is in the code above.





Aucun commentaire:

Enregistrer un commentaire