1,把bean里面的get方法上面的格式去掉 我的代码如下:private Timestamp time; public Timestamp getTime() { return time; } public void setTime(Timestamp time) { this.time = time; }测试方法:public static void main(String[] args) throws JsonProcessingException, Pars...
java ObjectMapper 将对象转换成json字符串问题
先给你一个正确的方法:
1,把bean里面的get方法上面的格式去掉
我的代码如下:
private Timestamp time; public Timestamp getTime() { return time; } public void setTime(Timestamp time) { this.time = time; }测试方法:
public static void main(String[] args) throws JsonProcessingException, ParseException { Timestamp timestamp = new Timestamp(System.currentTimeMillis()); AccountInfo accountInfo = new AccountInfo(); accountInfo.setTime(timestamp); ObjectMapper mapper = new ObjectMapper(); mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")); String s = mapper.writeValueAsString(accountInfo); System.out.println(s); long time = DateUtils.parseDate("1987-06-04 00:00:001","yyyy-MM-dd hh:mm:ss").getTime(); String date = DateUtils.parseDate("1987-06-04 00:00:01","yyyy-MM-dd hh:mm:ss").toString(); System.out.println(date); timestamp = Timestamp.valueOf("1987-06-04 00:00:00"); System.out.println(timestamp); accountInfo = new AccountInfo(); accountInfo.setTime(timestamp); mapper = new ObjectMapper(); mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")); s = mapper.writeValueAsString(accountInfo); System.out.println(s); }输出结果:
{"openId":null,"token":null,"ip":null,"account":null,"phone":null,"email":null,"platformType":0,"time":"2018-10-16 01:27:16"}Thu Jun 04 00:00:01 CDT 19871987-06-04 00:00:00.0{"openId":null,"token":null,"ip":null,"account":null,"phone":null,"email":null,"platformType":0,"time":"1987-06-04 12:00:00"}不过这里有一个小问题,因为你是使用的yyyy-MM-dd hh:mm:ss 格式,而hh表示按12小时计时,所以1987-06-04 00:00:00会在json中表示为1987-06-04 12:00:00,你可以换成yyyy-MM-dd HH:mm:ss按24小时计进即可。
2018-10-16