JSONArray.toCollection 封装 bean 失败
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> 处理方式一样