**JSON以及AJAX的学习**

JSON以及AJAX的学习

一、编写Controller,用来将集合、对象或日期封装成JSON字符串返回给客户端。

本文采用Jackson的方法进行封装。
首先需要引入相关依赖

<!-- https://mvnrepository.com/artifact/org.codehaus.jackson/jackson-core-asl -->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.5.0</version>
    </dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.5.0</version>
    </dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.5.0</version>
    </dependency>

下面展示一些 内联代码片

@RequestMapping(value = "/jsonLearning")   //,produces = {"application/json;charset=UTF-8"}
    @ResponseBody              //将服务器端的对象转换成json对象相应回去
    public String jsonLearning() throws JsonProcessingException {
        User user = new User();
        user.setUserId(3);
        user.setUsername("张三");
        user.setPassword("123456");
        user.setBirthday(new Date());
        //创建一个jackson对象,用来转换json格式    jackson的对象映射器
        ObjectMapper objectMapper = new ObjectMapper();
        String string = objectMapper.writeValueAsString(user);
        System.out.println(string);
        return string;   //由于使用了jackson的@ResponseBody,这里将string以json字符串格式返回,而不进入视图解析器
    }

通过在客户端访问,发现出现了中文乱码问题。可通过以下方法解决
1、修改@RequestMapping(value = “/jsonLearning”)
– >
@RequestMapping(value = “/jsonLearning”,produces = {“application/json;charset=UTF-8”})
2、从根源上解决,配置SpringMVC的配置文件:

<!-- 开启对SpringMVC注解的支持 -->
    <mvc:annotation-driven>
        <!--Json格式乱码处理方式-->
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg value="UTF-8"/>
            </bean>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="objectMapper">
                    <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
                        <property name="failOnEmptyBeans" value="false"/>
                    </bean>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
二、对于日期问题,需要如下代码进行控制
@RequestMapping(value = "/jsonTime")   //,produces = {"application/json;charset=UTF-8"}
    @ResponseBody              //将服务器端的对象转换成json对象相应回去
    public String jsonTime() throws JsonProcessingException {

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS,false);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        objectMapper.setDateFormat(sdf);
        String string = objectMapper.writeValueAsString(new Date());
        System.out.println(string);
        return string;   //由于使用了jackson的@ResponseBody,这里将string以json字符串格式返回,而不进入视图解析器
    }
三、为了方便,可以编写JsonUtils
package com.igeek.ssm.utils;

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

import java.text.SimpleDateFormat;

public class JsonUtils {

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

    private static String getJson(Object object, String datefromat) {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS,false);
        SimpleDateFormat sdf = new SimpleDateFormat(datefromat);
        objectMapper.setDateFormat(sdf);
        try {
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
}

四、jQuery编写

$.ajax({
                type: "POST",
                url: "test.json",
                data: {username:$("#username").val(), content:$("#content").val()},
                dataType: "json",
                success: function(data){
                    $('#resText').empty();   //清空resText里面的所有内容
                    var html = '';
                    $.each(data, function(commentIndex, comment){
                        html += '<div class="comment"><h6>' + comment['username']
                            + ':</h6><p class="para"' + comment['content']
                            + '</p></div>';
                    });
                    $('#resText').html(html);
                }
            });

            $.post("test.php", { "func": "getNameAndTime" },
                function(data){
                    alert(data.name); // John
                    console.log(data.time); //  2pm
                }, "json");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值