Java Map转对象

时间:2022-07-23
本文章向大家介绍Java Map转对象,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

今天遇到一个问题,前端一条数据大概有100多个字段,前端要求按照传参数返回,传了10个就只能返回10个字段的值,所以用对象就不太合适,会返回一些无用字段,所以只能用Map动态返给前端。

动态Sql

SELECT
     DATE_FORMAT(rtc_time, '%Y-%m-%d %H:%i') AS time,
    <foreach collection="factorList" item="factor" open="" separator="," close="">
        ${factor} AS ${factor}
    </foreach>
    FROM
        tb_xxx_data

这样前端传几个字段,sql就查几个字段。

但是在做数据导出的时候,就有个问题,导出Excel有一段代码

 //使首字母大写
String UTitle = Character.toUpperCase(title.charAt(0))
+ title.substring(1, title.length()); // 使其首字母大写;
String methodName = "get" + UTitle;
// 设置要执行的方法
Method method = clsss.getMethod(methodName);

用的是对象的Get方法取值。所以就需要把Map在转成对象,幸好fastjson提供了这样的方法。

 VocsData vocsData = JSONObject.parseObject(JSONObject.toJSONString(vocsMap),VocsData.class);

顺便提一下Java导Excel的方法,有需要的可以使用 使用的时候注意 titleName的顺序一定要和titleColumn的一致。不一致数据就错乱了。

/**
     * 写excel.
     *
     * @param titleColumn 对应bean的属性名
     * @param titleName   excel要导出的表名
     * @param titleSize   列宽
     * @param dataList    数据
     */
    public void wirteExcel(String titleColumn[], String titleName[], int titleSize[], List<?> dataList) {
        //添加Worksheet(不添加sheet时生成的xls文件打开时会报错)
        Sheet sheet = workbook.createSheet(this.sheetName);
        //新建文件
        OutputStream out = null;
        try {
            if (fileDir != null) {
                //有文件路径
                out = new FileOutputStream(fileDir);
            } else {
                //否则,直接写到输出流中
                out = response.getOutputStream();
                fileName = fileName + ".xlsx";
                response.setContentType("application/x-msdownload");
                response.setHeader("Content-Disposition",
                        "attachment; filename=" + new String(fileName.getBytes("UTF-8"), "ISO8859-1"));
            }

            //写入excel的表头
            Row titleNameRow = workbook.getSheet(sheetName).createRow(0);
            //设置样式
            CellStyle titleStyle = workbook.createCellStyle();
            titleStyle = (CellStyle) setFontAndBorder(titleStyle, titleFontType, (short) titleFontSize);
            // titleStyle = (CellStyle) setColor(titleStyle, titleBackColor, (short) 10);

            for (int i = 0; i < titleName.length; i++) {
                sheet.setColumnWidth(i, titleSize[i] * 256); //设置宽度
                Cell cell = titleNameRow.createCell(i);
                cell.setCellStyle(titleStyle);
                cell.setCellValue(titleName[i].toString());
            }

            //为表头添加自动筛选
            if (!"".equals(address)) {
                CellRangeAddress c = (CellRangeAddress) CellRangeAddress.valueOf(address);
                sheet.setAutoFilter(c);
            }

            //通过反射获取数据并写入到excel中
            if (dataList != null && dataList.size() > 0) {
                //设置样式
                CellStyle dataStyle = workbook.createCellStyle();
                titleStyle = (CellStyle) setFontAndBorder(titleStyle, contentFontType, (short) contentFontSize);
                DataFormat format = workbook.createDataFormat();
                dataStyle.setDataFormat(format.getFormat("@"));
                if (titleColumn.length > 0) {
                    for (int rowIndex = 1; rowIndex <= dataList.size(); rowIndex++) {
                        Object obj = dataList.get(rowIndex - 1); //获得该对象
                        Class<? extends Object> clsss = obj.getClass(); //获得该对对象的class实例
                        Row dataRow = workbook.getSheet(sheetName).createRow(rowIndex);
                        for (int columnIndex = 0; columnIndex < titleColumn.length; columnIndex++) {
                            String title = titleColumn[columnIndex].toString().trim();
                            if (!"".equals(title)) { //字段不为空
                                //使首字母大写
                                String UTitle = Character.toUpperCase(title.charAt(0))
                                        + title.substring(1, title.length()); // 使其首字母大写;
                                String methodName = "get" + UTitle;
                                // 设置要执行的方法
                                Method method = clsss.getMethod(methodName);
                                //获取返回类型
                                String returnType = method.getReturnType().getName();
                                String data = method.invoke(obj) == null ? "" : method.invoke(obj).toString();
                                Cell cell = dataRow.createCell(columnIndex);
                                CellStyle cellStyle = workbook.createCellStyle();
                                //全部用字符串写入excel避免小数格式显示不完整 0.08会展示成.08
                                if (data != null && !"".equals(data)) {
                                    if ("int".equals(returnType) || "java.lang.Integer".equals(returnType)) {
                                        cellStyle.setDataFormat(format.getFormat("#,#0"));
                                        cell.setCellStyle(cellStyle);
                                        cell.setCellValue(Integer.parseInt(data));
                                    } else if ("long".equals(returnType) || "java.lang.Long".equals(returnType)) {
                                        cellStyle.setDataFormat(format.getFormat("#,#0"));
                                        cell.setCellStyle(cellStyle);
                                        cell.setCellValue(Long.parseLong(data));
                                    } else if ("float".equals(returnType) || "java.lang.Float".equals(returnType)) {
                                        cellStyle.setDataFormat(format.getFormat("#,#0.00"));
                                        cell.setCellStyle(cellStyle);
                                        cell.setCellValue(Float.parseFloat(data));
                                    } else if ("double".equals(returnType) || "java.lang.Double".equals(returnType)) {
                                        cellStyle.setDataFormat(format.getFormat("#,#0.00"));
                                        cell.setCellStyle(cellStyle);
                                        cell.setCellValue(Double.parseDouble(data));
                                    } else {
                                        cell.setCellValue(data);
                                    }
                                }
                            } else { //字段为空 检查该列是否是公式
                                if (colFormula != null) {
                                    String sixBuf = colFormula[columnIndex].replace("@", (rowIndex + 1) + "");
                                    Cell cell = dataRow.createCell(columnIndex);
                                    cell.setCellFormula(sixBuf.toString());
                                }
                            }
                        }
                    }

                }
            }
            workbook.write(out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }