JSONArray.toCollection 封装 bean 失败

本文介绍了一种处理HTTP请求返回的长整型时间戳的方法,通过正则表达式将其转换为日期格式,并讨论了如何避免日期字段显示为当前时间的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 问题描述:

   通过http请求服务端, 返回的bean的集合的字符串形式, 其中bean中的Date类型的属性值,形式为Long类型的表示形式(1466083519000);

   String responseStr = client.list(userid, from, to, s, max, -1);

  返回的 responseStr如下:


[{"id":44,"content":"上海精神","createtime":1466083520000,"provider":"Apollo","receiver":"apollo","readingflag":1},{"id":45,"content":"上海精神","createtime":1466083520000,"provider":"Apollo","receiver":"apollo","readingflag":1},{"id":46,"content":"上海精神","createtime":1466083520000,"provider":"Apollo","receiver":"apollo","readingflag":1},{"id":47,"content":"上海精神","createtime":1466083520000,"provider":"Apollo","receiver":"apollo","readingflag":0},{"id":48,"content":"上海精神","createtime":1466083520000,"provider":"Apollo","receiver":"apollo","readingflag":0},{"id":49,"content":"上海精神","createtime":1466083520000,"provider":"Apollo","receiver":"apollo","readingflag":0},{"id":8,"content":"上海精神","createtime":1466083519000,"provider":"Apollo","receiver":"apollo","readingflag":1},{"id":9,"content":"上海精神","createtime":1466083519000,"provider":"Apollo","receiver":"apollo","readingflag":1},{"id":10,"content":"上海精神","createtime":1466083519000,"provider":"Apollo","receiver":"apollo","readingflag":1},{"id":13,"content":"上海精神","createtime":1466083519000,"provider":"Apollo","receiver":"apollo","readingflag":1}]

  此时通过JSONArray来转换,

  JSONArray jArray = JSONArray.fromObject(responseStr);

接着通过Collection collection = JSONArray.toCollection(jArray, Message.class);来转出集合,

问题出现了:

    集合 bean(Message)中的Date 类型 createtime值为系统当前时间, 而非正确的时间数据(1466083519000所对应的 yyyy-MM-dd类型数据)。

 

2. 处理办法:

   对返回的responseStr数据运用正则表达式,替换long形式数据为日期格式形式。

  

     String regEx = "[0-9]{13}";
        Pattern pattern = Pattern.compile(regEx);
        Matcher matcher = pattern.matcher(responseStr);
        while(matcher.find()){
            String group = matcher.group();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String format = sdf.format(new Date(Long.valueOf(group)));
            responseStr = responseStr.replace(group, format);
        }

        JSONArray jArray = JSONArray.fromObject(responseStr);
        List<Map> messageListPage = (List<Map>)JSONArray.toCollection(jArray, Map.class);
       

 再将List<Map> 返回前端 让js处理,前端返回类型 dataType : "json”, 返回List<Message> 和 返回 List<Map> 处理方式一样

转载于:https://www.cnblogs.com/rocky-fang/p/5718342.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值