我是徐大志

有志者事竟成,破釜沉舟,百二秦关终属楚;
苦心人天不负,卧薪尝胆,两千越甲可吞吴。

Gson转换复杂对象报错【类型强转错误】

一、问题:

  项目里遇到一个需求,规则文件下载后,导入本地解析。

  采用的方案是:获取复杂对象,使用谷歌Gson转换为字串保存为文件下载,客户端读取文件,解析字串,反解对象

  遇到的问题:传输的对象是一个嵌套的对象,反解的时候会报出类型强转异常

 

二、解决:

  参考网址:【Gson对象转成Java复杂对象出错】 

//规则生成
@RequestMapping(value = {"/getRuleFile"},method = RequestMethod.GET,produces = {"application/json"})
    public void getRuleFile(HttpServletRequest request, HttpServletResponse response,
                            @RequestParam(value = "orgId",required = false)String orgId){

        if(null==orgId || "".equals(orgId)){
            orgId = "";
        }
        List<Rule> ruleList = service.getRuleList(orgId);
        //转换为json
        String ruleStr = gson.toJson(ruleList);
        if("".equals(ruleStr)){
            log.error("转换json字串为空!获取的规则信息有:"+ruleList);
        }else{
            //下载文件
            response.setContentType("text/html;charset=gb2312");
            response.setHeader("Content-Disposition", "attachment; filename=rule.json");
            OutputStream out = null;
            ByteArrayInputStream in = null;
            try {
                out = response.getOutputStream();
                in = new ByteArrayInputStream(ruleStr.getBytes());
                int len = -1;
                byte[] temp = new byte[2048];
                while( (len = in.read(temp)) != -1){
                    out.write(temp,0,len);
                }
            }catch (Exception e){
                log.error("文件下载失败!要下载的文件字串为:"+ruleStr);
                e.printStackTrace();
            }finally {
                try {
                    in.close();
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

//文件转换
String filePath = "D://temp/rule.json";
String jsonStr = JsonUtils.readCheckFile(filePath);
List<Rule> ruleList = null;
//需要单独使用反射指定转换的对象类型 List
<Rule> rules = new Gson().fromJson(jsonStr, new TypeToken<List<Rule>>() {}.getType()); int i=0; for(Rule rule : rules) { System.out.println(rule.getCOLUMNRULES().get(i).getTC_RULE_CODE_VALUES()); i++; }

 

三、总结:

  遇到的这个问题,解决的方法很简单,但是网上的很多方法会误导我们。

  找到问题的根源:类型转换时,gson转换的类型和我们期望的类型不匹配,需要反射指定转换的匹配类型

 

posted @ 2018-06-28 10:23  我是徐大志  阅读(927)  评论(0编辑  收藏  举报
【少年,我看你目光炯炯有神,将来一定能成大事!】