关于页面显示JSON时间戳问题

JSON时间戳

后端返回前端JSON数据为时间戳,用封装和重载思想,写一个不返回时间戳工具类,调用这个方法,页面可以显示自己想要的时间样式,这里采用"yyyy-MM-dd HH:mm:ss"。

引用B站:狂神说

utils:

package com.godwin.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import java.text.SimpleDateFormat;

/**
 * 不返回时间戳
 * Created by Godwin on 2020/12/21.
 */
public class JsonUtils {

    public static String getJson(Object object){
        return getJson(object,"yyyy-MM-dd HH:mm:ss");
    }

    public static String getJson(Object object,String dataFormat){
        ObjectMapper mapper = new ObjectMapper();
        //1.如何让他不返回时间戳!所以我们要关闭它的时间戳功能
        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);
        //2.时间格式化问题!自定日期格式对象
        SimpleDateFormat sdf = new SimpleDateFormat(dataFormat);
        //3.让mapper指定时间日期格式为sdf
        mapper.setDateFormat(sdf);
        try {
            return mapper.writeValueAsString(object);
        }catch (JsonProcessingException e){
            e.printStackTrace();
        }
        return null;
    }
}

controller:

package com.godwin.controller;

import com.godwin.utils.JsonUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;

/**
 * Created by Godwin on 2020/12/21.
 */
@Controller
public class JsonController {

    @RequestMapping("/test")
    @ResponseBody//将java对象转换为json数据
    public String json(){
        Date date = new Date();
        return JsonUtils.getJson(date);
    }
}

运行项目,并打开网页输出:http://localhost:8080/test

点击此处直接进入http://localhost:8080/test

按照上述操作,网页会显示:

"2020-12-21 09:56:12"

posted @ 2020-12-21 10:01  Godwin_Zhang  阅读(256)  评论(0编辑  收藏  举报