如何使用杰克逊创建嵌套的json对象

rufusy:

我正在使用休眠从数据库查询用户记录,如下所示:

String hql = "SELECT U FROM User U";
List<User> users = this.em.createQuery(hql).getResultList();

如何将返回的数据转换为json,如下所示:

在此处输入图片说明

如果没有找到用户,我希望我的json如下所示:

在此处输入图片说明

我想在创建json数据之前对检索到的数据进行一些操作。因此,我想避免直接传递列表,如下所示:

 String data = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(users);
亚历克斯·鲁登科(Alex Rudenko):

如果使用的是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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章