json返回前端的乱码问题

在学习json解析的过程中,使用springmvc在前端返回一个jackson对象映射器将对象转换为json字符串时,引起乱码问题;
解决方法有两种:
一:使用 @RequestMapping(value="/*",produces = “application/json;charset = utf-8” )
二:使用配置(使用第三方Jackson的解决方法)

    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg value="UTF-8"/>
            </bean>
             <!--这个需要导入第三方Jackson包-->
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="ObjectMapper">
                    <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
                        <property name="failOnEmptyBeans" value="false"></property>
                    </bean>
                </property>
            </bean>
        </mvc:message-converters>

    </mvc:annotation-driven>

在进行java.util.date时间输出时,会转换成时间戳(Time stamp)格式(1609682783263)1970年1月1日到当前时间

  @RequestMapping(value="/time")
    @ResponseBody //将服务器端返回的对象转换为json对象响应回去
    public String json() throws JsonProcessingException {
        Date date = new Date();
        return new ObjectMapper().writeValueAsString(date);
    }

在这里插入图片描述
将其转换为:yyyy-MM-dd HH-mm-ss

@RequestMapping(value="/time1")
    @ResponseBody //将服务器端返回的对象转换为json对象响应回去
    public String json3() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        //1.关闭Jackson的时间戳功能
        mapper.configure(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS,false);
        //2.通过SimpleDateForMat进行时间格式的转换
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
        //3.通过setsetDateFormat()指定时间格式
        mapper.setDateFormat(simpleDateFormat);
        Date date = new Date();
        return mapper.writeValueAsString(date);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值