首页 > 其他分享 >【WEEK3】 【DAY3】JSON交互处理第二部分【中文版】

【WEEK3】 【DAY3】JSON交互处理第二部分【中文版】

时间:2024-03-17 21:30:13浏览次数:14  
标签:mapper json DAY3 6.6 JSON User new WEEK3 ObjectMapper

2024.3.13 Wednesday

接上文【WEEK3】 【DAY2】JSON交互处理第一部分【中文版】

目录

6.4.代码优化

6.4.1.乱码统一解决

  1. 上一种方法比较麻烦,如果项目中有许多请求则每一个都要添加,可以通过Spring配置统一指定,这样就不用每次都处理乱码了。可以在springmvc的配置文件上添加一段消息StringHttpMessageConverter转换配置。
  2. 修改springmvc-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- 自动扫描指定的包,下面所有注解类交给IOC容器管理 -->
    <context:component-scan base-package="P14.controller"/>

    <!--JSON乱码问题配置-->
    <mvc:annotation-driven>
        <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>

    <!-- 视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          id="internalResourceViewResolver">
        <!-- 前缀 -->
        <property name="prefix" value="/WEB-INF/jsp/" />
        <!-- 后缀 -->
        <property name="suffix" value=".jsp" />
    </bean>

</beans>

  1. 此时修改UserController.java至没有解决乱码问题(注释掉以下这行)的版本(便于检查该方法的有效性)
    //修正乱码问题
//    @RequestMapping(value = "/j1",produces = "application/json;charset=utf-8")
  1. 运行检查到乱码问题已解决
    http://localhost:8080/springmvc_05_json_war_exploded/j1
    在这里插入图片描述

6.4.2.返回JSON字符串统一解决

  1. 在类上直接使用 @RestController,使所有的方法都只返回 json 字符串,不用再在每个子方法处都添加@ResponseBody。在前后端分离开发中,一般都使用 @RestController,十分便捷
package P14.controller;

import P14.project.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

//@Controller//经过视图解析器
@RestController//不经过视图解析器,以下方法只会返回json字符串(作用域很广,故无需写第18行的@ResponseBody)
public class UserController {

    //修正乱码问题
//    @RequestMapping(value = "/j1",produces = "application/json;charset=utf-8")
    @RequestMapping("/j1")
//    @ResponseBody   //就不会经过视图解析器,会直接返回一个字符串
    public String json1() throws JsonProcessingException {
        //使用导入的jackson-databind包中的ObjectMapper
        ObjectMapper mapper = new ObjectMapper();

        //创建一个对象
        User user = new User("张三",11,"female");

        //将一个值转化为字符串
        String str = mapper.writeValueAsString(user);

        //由于@ResponseBody注解,这里会将str转成json格式返回;十分方便
        return str;
    }
}

  1. 运行结果同上,不多赘述

6.5.测试集合输出

6.5.1.在UserController.java中添加一个新方法json2

@RequestMapping("/j2_set")
    public String json2() throws JsonProcessingException {
        //使用导入的jackson-databind包中的ObjectMapper
        ObjectMapper mapper = new ObjectMapper();

        //创建集合
        List<User> userList = new ArrayList<>();
        User user1 = new User("张三",11,"female");
        User user2 = new User("李四",11,"male");
        User user3 = new User("王五",11,"female");
        //将user加入集合
        userList.add(user1);
        userList.add(user2);
        userList.add(user3);

        //将一个集合转化为字符串
        String str = mapper.writeValueAsString(userList);

        //返回多个对象
        return str; //等效于返回new ObjectMapper().writeValueAsString(userList)
    }

6.5.2.运行

http://localhost:8080/springmvc_05_json_war_exploded/j2_set
在这里插入图片描述

6.6.输出时间对象

6.6.1.在UserController.java中添加一个新方法json3

@RequestMapping("/j3_time")
    public String json3() throws JsonProcessingException {
        //使用导入的jackson-databind包中的ObjectMapper
        ObjectMapper mapper = new ObjectMapper();
        //注意导入的是java.util包
        Date date = new Date();
					//ObjectMapper得到将时间解析后的默认格式,为timestamp
        return  mapper.writeValueAsString(date);
    }

6.6.2.运行

http://localhost:8080/springmvc_05_json_war_exploded/j3_time
在这里插入图片描述
运行得到的一串数字是时间戳,是Jackson 默认的时间转换形式。时间戳指:从1970年1月1日(UTC/GMT的午夜)开始所经过的秒数,不考虑闰秒。参考链接:https://tool.lu/timestamp/

6.6.3.更改输出时间的方式

在上述基础上添加一个方法,使输出的时间以自定的方式出现

6.6.3.1.Java解决法

  1. 新建json4
@RequestMapping("/j4_time")
    public String json4() throws JsonProcessingException {
        //使用导入的jackson-databind包中的ObjectMapper
        ObjectMapper mapper = new ObjectMapper();

        //注意导入的是java.util包
        Date date = new Date();

        //使用自定义日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        //ObjectMapper得到将时间解析后的默认格式,为timestamp
        return  mapper.writeValueAsString(sdf.format(date));
    }
  1. 运行
    http://localhost:8080/springmvc_05_json_war_exploded/j4_time
    在这里插入图片描述

6.6.3.2.ObjectMapper格式化输出

  1. 新建json5
@RequestMapping("/j5_time")
    public String json5() throws JsonProcessingException {
        //使用导入的jackson-databind包中的ObjectMapper
        ObjectMapper mapper = new ObjectMapper();
        //使用ObjectMapper格式化输出
        //关闭使用时间戳
        mapper.configure(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS,false);
        //使用自定义日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //自定义了新的时间戳使用方式
        mapper.setDateFormat(sdf);

        //注意导入的是java.util包
        Date date = new Date();

        //ObjectMapper得到将时间解析后的默认格式,为timestamp
        return  mapper.writeValueAsString(date);
    }
  1. 运行
    http://localhost:8080/springmvc_05_json_war_exploded//j5_time
    在这里插入图片描述

标签:mapper,json,DAY3,6.6,JSON,User,new,WEEK3,ObjectMapper
From: https://blog.csdn.net/2401_83329143/article/details/136695372

相关文章

  • C++ 简单使用Json库与muduo网络库
    C++简单使用Json库与muduo网络库C++使用Json库测试代码均在Ubuntu20上运行首先下载json.hpp的代码链接然后和你的测试代码放在同一目录下面导入方式#include"json.hpp"usingjson=nlohmann::json;json序列化代码测试1voidtest1(){jsonjs;js["id"]={1......
  • Leecode Day3
    初始想法也是用双指针,问题在于没有灵活运用与运算(实现求和后结果满足二进制表达形式),未设置加位!(add);多了索引位置i,只需要指针i和j。当前位为空。错误代码如下:学习画图小匠的代码:https://leetcode.cn/problems/add-binary/solutions/2652640/javapython3cwei-yun-suan-s......
  • nicetool--替代hutool和fastjson的工具库
    ​前言如果你被hutool坑过、被fastjson坑过,nicetool帮你解脱!如果你想用稳定、Spring原生的工具类,nicetool已帮你封装!nicetool不生产工具,只是JDK和Spring的封装侠!介绍nicetool:超好用的Java工具类:稳定、方便。最大程度利用SpringBoot原生工具。官网:https://www.yuque.com/kni......
  • PgSql jsonb类型查询
    十年河东,十年河西,莫欺少年穷学无止境,精益求精json函数及操作,详情请参考:http://www.postgres.cn/docs/12/functions-json.html表结构如下:createtablechargeing(idUUIDprimarykeynotnull,heartjsonbnotnull,createtimetimestampnotnull);createindex......
  • fastjson1.2.24-RCE漏洞复现
    触发过程图靶场模拟1、实验环境准备攻击者kali(192.168.101.141)使用工具:marshalsec-0.0.3-SNAPSHOT-all.jarGitHub-RandomRobbieBF/marshalsec-jar:marshalsec-0.0.3-SNAPSHOT-allcompiledonX64被攻击者centos7(192.168.101.148)使用工具:dockerdocker-compose......
  • MeterSphere接口自动化系列之JSONPath常用提取方式
    一、使用场景        针对接口返回结果,提取相应的信息,用于后续接口输入或用于执行结果断言,对应平台的后置操作、断言规则页签。        二、常用方式实例接口返回结果{"code":0,"data":{"cart":{"id":"34253627754......
  • 08JSON格式
    1<!DOCTYPEhtml>2<htmllang="en">3<head>4<metacharset="UTF-8">5<metaname="viewport"content="width=device-width,initial-scale=1.0">6<title>Document......
  • json总结 fastjson和jackson 以及typereference(未写完)
    fastjson跟JackJson有很大区别,为了防止搞混,这里进行总结因为会涉及到流水线的门禁,所以这里给出比较优质的解决方案 两个测试类代码如下:@DatapublicclassStudent{privateStringname;privateIntegerage;privateTeacherteacher;}@Datapubl......
  • Rust解析JSON,结构体序列化和反序列化
    Rust参考教程:HereJSON一种常用的由键值对组成的数据对象;本文将通过多个例子讲解在Rust中如何解析JSON内容,以及如何将结构体转换成JSON字符串。在Rust中解析JSON文本通常需要使用一个JSON库。Rust标准库中有一个名为serde的库,它提供了序列化和反序列化结构体和其他数据类型的......
  • fastjson改造
    背景fastjson太过于侧重性能,对于部分高级特性支持不够,而且部分自定义特性完全偏离了json和js规范导致和其他框架不兼容;fastjson文档缺失较多,部分Feature甚至没有文档,而且代码缺少注释较为晦涩;fastjson的CVEbug监测较弱,很多CVE数据库网站上有关fastjson的CVE寥寥无几,例如近......