java ObjectMapper 将对象转换成json字符串问题

在转换时候,timestamp类型的字段,有相差8小时,有相差9小时直接上代码了,感兴趣的大神能不能给一个答案

先给你一个正确的方法:

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 1987
1987-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小时计进即可。

温馨提示:答案为网友推荐,仅供参考

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网