我正在使用hibernate从数据库查询用户记录,如下所示:
String hql = "SELECT U FROM User U";
List<User> users = this.em.createQuery(hql).getResultList();
如何将返回的数据转换为json,如下所示:
如果未找到用户,我希望我的json如下所示:
我想在创建json数据之前对检索到的数据进行一些操作。因此,我想避免直接通过列表,如下所示:
String data = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(users);
答案 0 :(得分:0)
您可以简单地逐步构建json:
第一步,我建议在User
类中创建一个方法,该方法将用户的名称和电子邮件作为json。
public class User{
...
public String getJsonUserEmail(){
return "{\"name\": \"" + this.getName() + "\", " +
"\"email\": \"" + this.getEmail() + "\"}"
}
...
}
将所有用户转换为json并构建最后一个json。
public static void main(String[] args) {
String finalJson = "{";
if(!users.isEmpty()){
finalJson += "\"usersFound\": true, ";
//transform every user to json
//{"name": "name1", "email": "email1"}
List<String> usersJson = users.stream()
.map(e -> e.getJsonUserEmail())
.collect(Collectors.toList());
//join all jsons
//{"name": "name1", "email": "email1"}, {"name": "name2", "email": "email2"}, ...
String usersJsonJoin = String.join(", ", usersJson);
finalJson += "\"users\": [" + usersJsonJoin + "]";
}else{
finalJson += "\"usersFound\": false, ";
finalJson += "\"msg\": \"No users found\"";
}
finalJson += "}";
}
答案 1 :(得分:0)
如果您正在使用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", "jack@mail.com"), new User("john", "john@mail.com"))
)));
System.out.println("null -> " + writer.writeValueAsString(buildUserListJson(null)));
System.out.println("empty -> " + writer.writeValueAsString(buildUserListJson(Collections.emptyList())));
输出:
{
"usersFound" : true,
"users" : [ {
"name" : "jack",
"email" : "jack@mail.com"
}, {
"name" : "john",
"email" : "john@mail.com"
} ]
}
null -> {
"usersFound" : false,
"msg" : "No User Found"
}
empty -> {
"usersFound" : false,
"msg" : "No User Found"
}