如果使用的是Jackson库,则应实现一个简单的DTO对象,该对象包含User
/ UserDto
列表,带有自定义msg
属性的空列表的存根,然后根据可用结果创建适当的实例。
您也可以使用@JsonPropertyOrder
注释设置生成的JSON中属性的顺序。
public class UserDto {
private final String name;
private final String email;
public UserDto(String name, String email) {
this.name = name;
this.email = email;
}
public String getName() { return this.name; }
public String getEmail() { return this.email; }
}
@JsonPropertyOrder({ "usersFound", "users" })
public class ListUserDto {
private final List<UserDto> users;
public ListUserDto(List<UserDto> users) {
this.users = users;
}
public List<UserDto> getUsers() {
return new ArrayList<>(users);
}
@JsonProperty("usersFound")
public boolean isUsersFound() {
return true;
}
}
@JsonPropertyOrder({ "usersFound", "msg" })
@JsonIgnoreProperties(value = {"users"})
public class EmptyListUserDto extends ListUserDto {
public EmptyListUserDto() {
super(Collections.emptyList());
}
public String getMsg() {
return "No User Found";
}
@JsonProperty("usersFound")
public boolean isUsersFound() {
return false;
}
}
// -------------
public ListUserDto buildUserListJson(List<User> users) {
// String hql = "SELECT U FROM User U";
// List<User> users = this.em.createQuery(hql).getResultList();
if (null == users || users.isEmpty()) {
return new EmptyListUserDto();
}
return new ListUserDto(
users.stream()
.map(u -> new UserDto(u.getName(), u.getEmail()))
.collect(Collectors.toList())
);
}
测试代码:
ObjectWriter writer = new ObjectMapper().writerWithDefaultPrettyPrinter();
System.out.println(writer.writeValueAsString(buildUserListJson(
List.of(new User("jack", "[email protected]"), new User("john", "[email protected]"))
)));
System.out.println("null -> " + writer.writeValueAsString(buildUserListJson(null)));
System.out.println("empty -> " + writer.writeValueAsString(buildUserListJson(Collections.emptyList())));
输出:
{
"usersFound" : true,
"users" : [ {
"name" : "jack",
"email" : "[email protected]"
}, {
"name" : "john",
"email" : "[email protected]"
} ]
}
null -> {
"usersFound" : false,
"msg" : "No User Found"
}
empty -> {
"usersFound" : false,
"msg" : "No User Found"
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句