JAVA WEB中利用@responsebody返回json

引言

如果我们现在做的项目如果不大,或者对美观要求度不高我们都会使用一些前台的框架比如说easyui,boostrapt。这后台就要给前台提供json数据,在一些app开发中也是如此....

需要使用的jar包

        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-core-lgpl</artifactId>
            <version>1.9.6</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-core-asl</artifactId>
            <version>1.9.4</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.5</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-lgpl</artifactId>
            <version>1.9.6</version>
        </dependency>

在spring-web.xml里面需要配置

<bean id="jackson2MessageConverter"
        class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>application/json;charset=UTF-8</value>
                <value>text/html;charset=UTF-8</value><!-- 避免IE出现下载JSON文件的情况 -->
            </list>
        </property>
    </bean>

如果我们时间需要格式化 我们需要配置一个
类型转换器

public class CustomObjectMapper extends ObjectMapper {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    public CustomObjectMapper() {
        this.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    }



}

然后修改spring-web.xml

<bean id="CustomObjectMapper" class="com.chaojimanong.os.common.Mapper.CustomObjectMapper" />
    <bean id="jackson2MessageConverter"
        class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
        <property name="objectMapper" ref="CustomObjectMapper"/>
        <property name="supportedMediaTypes">
            <list>
                <value>application/json;charset=UTF-8</value>
                <value>text/html;charset=UTF-8</value><!-- 避免IE出现下载JSON文件的情况 -->
            </list>
        </property>
    </bean>

最后看看效果
这里写图片描述
时间已经完全格式化,而且我们返回的数据是json

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值