欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java按照指定格式数据封装

程序员文章站 2022-07-13 11:54:51
...

一、需求

1、数据库表
java按照指定格式数据封装
2、按照如下格式进行数据分装:

 {
      {
        "id": "1178214681181483010",
        "title": "一级分类",
        "children": [
          {
            "id": "1178214681210843137",
            "title": "二级分类"
          }
        ]
      },
}

二、解决方式

1、创建数据库表实体类

@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@ApiModel(value="EduSubject对象", description="课程科目")
public class EduSubject implements Serializable {

    private static final long serialVersionUID=1L;

    @ApiModelProperty(value = "课程类别ID")
      @TableId(value = "id", type = IdType.ASSIGN_ID)
    private String id;

    @ApiModelProperty(value = "类别名称")
    private String title;

    @ApiModelProperty(value = "父ID")
    private String parentId;

    @ApiModelProperty(value = "排序字段")
    private Integer sort;

    @ApiModelProperty(value = "创建时间")
    @TableField(fill = FieldFill.INSERT)
    private Date gmtCreate;

    @ApiModelProperty(value = "更新时间")
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date gmtModified;

}

2、根据返回数据创建一级分类实体类

/**
 * 一级分类
 * @Author jzd
 * @Date 2020/8/2 15:07
 */
@Data
public class OneSubject {
    private String id;
    private String title;

    //一个一级分类有多个二级分类
    private List<TwoSubject> children = new ArrayList<>();
}

3、根据返回数据创建二级分类实体类

/**
 * 二级分类
 * @Author jzd
 * @Date 2020/8/2 15:07
 */
@Data
public class TwoSubject {
    private String id;
    private String title;
}

3、编写具体封装

//课程分类列表
@Override
public List<OneSubject> getOneTwoSubject() {
    //查询出所有一级分类 parentId = 0
    QueryWrapper<EduSubject> wrapperOne = new QueryWrapper<>();
    wrapperOne.eq("parent_id","0");
    List<EduSubject> oneSubjectList  = baseMapper.selectList(wrapperOne);

    //查询出所有二级分类 parentId != 0
    QueryWrapper<EduSubject> wrapperTwo = new QueryWrapper<>();
    wrapperOne.ne("parent_id","0");
    List<EduSubject> twoSubjectList  = baseMapper.selectList(wrapperTwo);

    //封装一级分类
    List<OneSubject> finalSubjectList = new ArrayList<>();
    for (int i = 0; i <oneSubjectList.size() ; i++) {
        EduSubject eduSubject = oneSubjectList.get(i);
        OneSubject oneSubject = new OneSubject();
        BeanUtils.copyProperties(eduSubject,oneSubject);
        finalSubjectList.add(oneSubject);
        //封装二级分类
        List<TwoSubject> twoFinalSubjectList = new ArrayList<>();
        for (int j = 0; j < twoSubjectList.size(); j++) {
            EduSubject eduSubject2 = twoSubjectList.get(j);
            if (eduSubject2.getParentId().equals(eduSubject.getId())) {
                TwoSubject twoSubject = new TwoSubject();
                BeanUtils.copyProperties(eduSubject2,twoSubject);
                twoFinalSubjectList.add(twoSubject);
            }
        }
        oneSubject.setChildren(twoFinalSubjectList);
    }
    return finalSubjectList;
}

三、总结

java按照指定格式数据封装