04SpringMVC--JSON使用

目录

JSON的要求和语法格式:

JSON字符串转化为JS对象,使用JSON.parse()方法

JS字符串转化为JSON对象,使用JSON.stringify()方法

 JSON 返回字符串

JSON处理时间Date

封装成工具类


JSON的要求和语法格式:

  • 对象表示为键值对
  • 数据由逗号分割,最后一组数据没有逗号
  • 花括号{}保存对象
  • 方括号[]保存数组
{"name":"秦江","age":3,"sex":"男"}

JSON键值对是用来保存JS对象的一种方式,和JS对象的写法也大同小异,键/值对组合中的键名写在前面并用双引号 ""包裹,使用冒号;分割。然后紧接着值:

   {"name":"秦江"}
   {"age":3}
   {"sex":"男"}

JSON和JS对象相互转换

JSON字符串转化为JS对象,使用JSON.parse()方法

var obj = JSON.parse('{"a":"hello","b":"Word"}'); //结果为 {a:'Hello',b:'Word'}

JS字符串转化为JSON对象,使用JSON.stringify()方法

var obj = JSON.stringify(a:'Hello',b:'Word'); //结果为 '{"a":"hello","b":,"Word"}'

 JSON 返回字符串

1、引入jar包

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

2、使用@ResponseBody

        使用位置在方法的上面

@ResponseBody,将服务器端返回的对象转换为对json对象响应回去;

3、需要一个jackson的对象映射器,就是一个类,使用它可以直接将对象转换为json字符串;

 ObjectMapper mapper = new ObjectMapper();

案例:

    @RequestMapping(value = "/json1")
    @ResponseBody
    public String json1() throws JsonProcessingException {
        
        ObjectMapper mapper = new ObjectMapper();

        User user = new User("秦疆1号", 1, "男");
        // 将Java对象转换为json字符串;
        String str = mapper.writeValueAsString(user);
        return str;
    }

发现问题:

        会有乱码问题

解决方案:

1、通过@RequestMaping的produces属性来实现

@RequestMapping(value = "/json1",produces = "application/json;charset=utf-8")

2、xml中配置

   <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>

JSON处理时间Date

        //1.如何让他不返回时间戳!所以我们要关闭他的时间功能
        mapper.configure(SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS, false);
        //2.时间格式化问题!自定义时间格式对象
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //3.让mapper指定时间日期格式为
        mapper.setDateFormat(sdf);

案例:

    @RequestMapping(value = "/time2")
    @ResponseBody
    public String time2() throws JsonProcessingException {

        ObjectMapper mapper = new ObjectMapper();
        //1.如何让他不返回时间戳!所以我们要关闭他的时间功能
        mapper.configure(SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS, false);
        //2.时间格式化问题!自定义时间格式对象
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //3.让mapper指定时间日期格式为
        mapper.setDateFormat(sdf);

        //写一个日期时间的类
        Date date = new Date();

        return mapper.writeValueAsString(date);
    }

封装成工具类

public class JsonUtils {

    /**
     * 默认时间格式 yyyy-MM-dd HH:mm:ss
     * @param object
     * @return
     */
    public static String getJson(Object object){
        return getJson(object, "yyyy-MM-dd HH:mm:ss");
    }


    /**
     * 自己定义时间格式
     * @param object
     * @param dateFormat
     * @return
     */
    public static String getJson(Object object,String dateFormat){
        ObjectMapper mapper = new ObjectMapper();
        //1.如何让他不返回时间戳!所以我们要关闭他的时间功能
        mapper.configure(SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS, false);
        //2.时间格式化问题!自定义时间格式对象
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        //3.让mapper指定时间日期格式为
        mapper.setDateFormat(sdf);

        try {
            return mapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

}

个人观点,有不足之处,请大家多批评改正

  • 8
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

gh-xiaohe

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值