json的学习

 json和对象之间的转换

        var obj = JSON.parse('{"a":"hello","b":"world"}');
        console.log(obj);
        const json = JSON.stringify({a:'hello',b:'world'});
        console.log(json);

 json的简述

服务于ajax,ajax可以进行异步请求,返回的是json字符格式

一个小呆萌

@RequestMapping("json1")
    public String json1() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        //创建对象
        Demo demo = new Demo(1,"小张");
        System.out.println(demo);
        //转换为json字符串
        String str = mapper.writeValueAsString(demo);
        System.out.println(str);
        return str;
    }

返回时间类型的json (时间戳)

@RequestMapping("json2")
    public String json2() throws JsonProcessingException {
        Date date = new Date();
        return new ObjectMapper().writeValueAsString(date);
    }

修改时间格式

@RequestMapping("json3")
    public String json3() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        //关闭时间戳
        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);
        //设置时间格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //指定设置后的格式
        mapper.setDateFormat(sdf);
        //时间对象
        Date date = new Date();
        return mapper.writeValueAsString(date);
    }

封装

@RequestMapping("json4")
    public String json4() throws JsonProcessingException {
        Date date = new Date();
        return JsonUtils.getJson(date);
    }

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 dateFormat){
        try{
            ObjectMapper mapper = new ObjectMapper();
            //关闭时间戳
            mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);
            //设置时间格式
            SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
            //指定设置后的格式
            mapper.setDateFormat(sdf);
            return mapper.writeValueAsString(object);
        }catch (JsonProcessingException e){
            e.printStackTrace();
        }
        return null;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值