如何从Spring上已定义的响应生成自定义消息



我的API返回给我这个:

[
{
"id": 1,
"uuid": "@B7304",
"username": "blabla",
"hearthBeat": 30,
"status": "well",
"date": "13/05/1333",
"latitute": 30,
"longitude": 40,
"cardiacSteps": 50
},
{
"id": 2,
"uuid": "@B7304",
"username": "blabla",
"hearthBeat": null,
"status": null,
"date": null,
"latitute": null,
"longitude": null,
"cardiacSteps": null
}
]

问题是,我想,在由第二个ID表示的数组上,返回一个错误消息,因为其中没有数据。像这样:

[
{
"id": 1,
"uuid": "@B7304",
"username": "blabla",
"hearthBeat": 30,
"status": "well",
"date": "13/05/1333",
"latitute": 30,
"longitude": 40,
"cardiacSteps": 50
},
{
"uuid": @B7304,
"message": "This user has no data"
}
]
我的代码如下:
@GetMapping("/monitored")
@PreAuthorize("hasRole('USER') and hasRole('RESPONSIBLE')")
public Object returnMonitored() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
Optional<User> username = userRepository.findByUsername(auth.getName());
List<Dependency> uuids = dependencyRepository.returnAllUserUuid(Objects.requireNonNull(username.orElse(null)).getUuid());
List<Health> health = new ArrayList<>();
uuids.forEach(uuid -> {
if (userRepository.existsByUuid(uuid.getUserUuid()) && healthRepository.existsByUuid(uuid.getUserUuid())) {
if(healthRepository.existsByUuid(uuid.getUserUuid()) && healthRepository.isRegistered(uuid.getUserUuid())) {
List<Health> healthList = healthRepository.returnAllUserUuid(uuid.getUserUuid());
health.addAll(healthList);
}
}
}
);
if(health == null || health.isEmpty()) {
return ResponseEntity.ok().body(new MessageVo("You're not responsible for any user ;) "));
}
return health;
}

有了这个,我似乎无法覆盖特定的响应,因为它是实体(健康)的列表。

谢谢你的帮助!

你要做的是真正的这是一个坏主意,因为人们希望JSON数组中的所有元素都具有相同的属性。

你应该返回你现在返回的所有null,并返回你的"消息"在地位。

[
{
"id": 1,
"uuid": "@B7304",
"username": "blabla",
"hearthBeat": 30,
"status": "well",
"date": "13/05/1333",
"latitute": 30,
"longitude": 40,
"cardiacSteps": 50
},
{
"id": 2,
"uuid": "@B7304",
"username": "blabla",
"hearthBeat": null,
"status": "This user has no data",
"date": null,
"latitute": null,
"longitude": null,
"cardiacSteps": null
}
]

我还建议添加"statusCode"属性,您可以在其中返回数字代码并具有"状态"。表示statusCode描述,因为对状态进行字符串比较也不是一个好主意。

在您的健康类中,添加@JsonInclude(Include.NON_NULL), null值将不会显示在您的响应中。注意使用盒装类型,而不是原始类型。

@JsonInclude(Include.NON_NULL)
public class Health {
Integer id;
String uuid;
... 
String message;
}

相关内容

  • 没有找到相关文章

最新更新