【发布时间】:2022-01-02 02:18:26
【问题描述】:
我有一个看起来像这样的模型:
@Data
public class RegistrationRequestDto {
public final String email;
public final String username;
public final String password;
public final String confirmPassword;
public final String firstName;
public final String lastName;
public final String keycloakId;
public RegistrationRequestDto(
String email,
String username,
String password,
String confirmPassword,
String firstName,
String lastName,
String keycloakId) {
notNull(email, "email must be set");
notNull(username, "username must be set");
notNull(password, "password must be set");
notNull(firstName, "firstName must be set");
notNull(lastName, "lastName must be set");
this.email = email;
this.username = username;
this.password = password;
this.confirmPassword = confirmPassword;
this.firstName = firstName;
this.lastName = lastName;
this.keycloakId = keycloakId;
}
}
接下来,我有一个方法用restTempate 调用另一个服务。
该调用的结果我应该保存在上面显示的模型中。
我有这段代码应该从外部服务调用并返回结果:
RegistrationRequestDto userProfile = new RegistrationRequestDto();
try {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
// httpHeaders.set("Authorization", "Bearer " + responseToken.getAccess_token());
HttpEntity<String> request = new HttpEntity<String>(httpHeaders);
ResponseEntity<Object> result = restTemplate.exchange(uri, HttpMethod.POST, request, Object.class);
log.info("{}", result);
log.info("{}", result.getBody());
LinkedHashMap<String, Object> map = (LinkedHashMap<String, Object>) result.getBody();
if (map != null) {
userProfile.setUserId(map.get("sub").toString());
userProfile.setGiven_name(map.get("given_name").toString());
userProfile.setFamily_name(map.get("family_name").toString());
userProfile.setEmail(map.get("email").toString());
userProfile.setEmail_verified(map.get("email_verified").toString());
//userProfile.setPhoto(Optional.ofNullable(map.get("photo").toString()));
}
} catch (Exception e) {
e.printStackTrace();
}
return userProfile;
所以,在这段代码中我正在使用
if (map != null) {
userProfile.setUserId(map.get("sub").toString());
userProfile.setGiven_name(map.get("given_name").toString());
userProfile.setFamily_name(map.get("family_name").toString());
userProfile.setEmail(map.get("email").toString());
userProfile.setEmail_verified(map.get("email_verified").toString());
}
当 RegistrationRequestDto 模型中的变量只是 private 时,我可以使用它。
但是现在变量是public final我不知道如何将结果存储在地图中?
【问题讨论】:
-
DTO 上的
@Data注释是什么?是龙目岛吗? -
是的,它是龙目岛
-
为什么不创建合约类并在交换方法中传递该类类型。它会给你解析的对象而不是地图。
-
@Pirate 我该怎么做?您是否有我可以查看的示例代码?
-
最终变量只能初始化一次。在调用代码中,您创建了一个新的 DTO,但没有参数,这是有效的(尽管我不知道为什么 notNull 调用不会阻止这一点。)然后您尝试针对已经初始化的变量运行单个设置器。
标签: java spring-boot linkedhashmap