0
点赞
收藏
分享

微信扫一扫

json的学习

是波波呀 2022-04-30 阅读 44

Ajax和Json

Web1.0时代

登录,如果失败,需要刷新页面,才能重新登录;不点击提交按钮,就不知道自己密码输错了;

现在大多数的网站,都是局部刷新,不刷新整个页面的情况下,实现页面更新;

注册的时候,发现手机以及注册过了,但是你只是输入了,没有提交,然后他就提示了。

Web2.0时代,最重要的一个因数就是Ajax。

JSON(JavaScript Object Notation,JS对象标记),是一种轻量级的数据交换格式。

采用完全独立于编程语言的文本格式来存储和表示数据。简洁和清晰掉的层次使得JSON成为理想的数据交换语言。易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率。

在JS语言中,一切都是对象。因此,任何JS支持的类型都可以通过JSON来表示,例如字符串、数字、对象、数组。他的要求和语法格式:

  • 对象表示为键值对
  • 数据由逗号分隔,最后一个不加逗号
  • 花括号{}保存对象
  • 方括号[]保存数组

JSON键值对,键值都用双引号包裹,中间用冒号分隔

{"name":"wakeuplb"}
{"age":"1"}
{"sex":"男"}

JSON和Js的关系,可以这么理解:JSON是JS对象的字符串表示法,它使用文本表示一个JS对象的信息,本质是一个字符串。相当于java中的toString()方法。

var obj = {a:'hello',b:'world'};//这是一个对象,注意键名也是可以使用引号包裹的
var json = '{"a":"hello","b":"world"}';//这是一个JSON字符串,本质是一个字符串

JSON和JS对象互转

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

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

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

var json = JSON.stringify({a:'hello',b:'world'});//结果是'{"a":"hello","b":"world"}'

JSON

json1.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script type="text/javascript">
  //编写一个对象
  var user = {
    name:"wakeuplb",
    age:1,
    sex:"男"
  };
  //输出这个对象
  console.log(user);//{name: 'wakeuplb', age: 1, sex: '男'}

  //js转为json字符串,使用JSON。stringify()方法
  var json = JSON.stringify(user);
  console.log(json);//{"name":"wakeuplb","age":1,"sex":"男"}

  //json转为js对象,使用JSON.parse()方法
  var js = JSON.parse(json);
  console.log(js);//{name: 'wakeuplb', age: 1, sex: '男'}


  var json2 = '{"a":"hello","b":"world"}';
  var js2 = JSON.parse(json2);
  console.log(js2);//{a: 'hello', b: 'world'}

  var obj2 = {a:'hello',b:'world'};
  var json2 = JSON.stringify(obj2);
  console.log(json2);//{"a":"hello","b":"world"}
</script>

</body>
</html>

结果:

在这里插入图片描述

在这里插入图片描述

pom.xml

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>org.example</groupId>
  <artifactId>demo_springmvc_ajax_json</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>demo_springmvc_ajax_json Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>

    </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-webmvc</artifactId>
          <version>5.0.8.RELEASE</version>
          <scope>compile</scope>
      </dependency>

    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.8</version>
    </dependency>


  </dependencies>


</project>

web.xml

<?xml version="1.0" encoding="UTF-8" ?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
         id="WebApp_ID" version="2.4"
>

    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!--配置过滤器-->
    <filter>
        <filter-name>myFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>

    <!--/*包括.jsp-->
    <filter-mapping>
        <filter-name>myFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

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/beans"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/spring-mvc.xsd">

    <context:component-scan base-package="com.lb.controller"/>


    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>
package com.lb.pojo;

public class User{
    private String name;
    private int age;
    private String sex;

    public User() {
    }

    public User(String name, int age, String sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", sex='" + sex + '\'' +
                '}';
    }
}

UserController

package com.lb.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.lb.pojo.User;
import com.lb.utils.JsonUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller//标志为控制器
public class UserController {

    @RequestMapping("/json1")
    //思考问题:我们正常返回他会走视图解析器,而json需要返回的是一个字符串
    //第三方jar包可以实现这个功能,jackson,只需要一个注解就可以实现了;
       // <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->

    //@ResponseBody ,   将服务器端返回的对象转换为json字符串响应回去;
    //@RequestBody
    @ResponseBody
    public String json1() throws JsonProcessingException {
        //需要一个jackson的对象映射器,本质就是一个类,使用它可以直接将对象转换为json字符串;
        ObjectMapper mapper = new ObjectMapper();

        //创建一个对象
        User user = new User("wakeup",3,"男");

        //将Java对象转换为json字符串;
        String s = mapper.writeValueAsString(user);
        System.out.println(s);

        return s;//由于使用了@ResponseBody注解,这里将s以json格式的字符串返回

    }

    //发现一个问题,乱码了,怎么解决?给RequestMapping加一个属性
    //发现出现了乱码问题,我们需要设置一下他的编码格式为utf-8,以及它返回的类型;
    //通过@RequestMapping的produces属性来实现,修改如下代码
    //produces:指定响应体返回类型和编码
    @RequestMapping(value = "/json2",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String json2() throws JsonProcessingException {

        User user = new User("wakeup",3,"男");
        //精简
        return new ObjectMapper().writeValueAsString(user);

    }

    @RequestMapping(value = "/json3",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String json3() throws JsonProcessingException {

        List<User> list = new ArrayList<User>();

        User user = new User("wakeup",3,"男");
        User user2 = new User("wakeup",3,"男");
        User user3 = new User("wakeup",3,"男");
        User user4 = new User("wakeup",3,"男");

        list.add(user);
        list.add(user2);
        list.add(user3);
        list.add(user4);


        return new ObjectMapper().writeValueAsString(list);
        /**
         * [
         *   {
         *     "name": "wakeup",
         *     "age": 3,
         *     "sex": "男"
         *   },
         *   {
         *     "name": "wakeup",
         *     "age": 3,
         *     "sex": "男"
         *   },
         *   {
         *     "name": "wakeup",
         *     "age": 3,
         *     "sex": "男"
         *   },
         *   {
         *     "name": "wakeup",
         *     "age": 3,
         *     "sex": "男"
         *   }
         * ]
         */
    }

    @RequestMapping(value = "/time1",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String json4() throws JsonProcessingException {

        Date date = new Date();
        System.out.println(date);

        //发现问题:时间默认返回的json字符串变成了时间戳的格式:1651327193091 Timestamp。
        return new ObjectMapper().writeValueAsString(date);

    }

    @RequestMapping(value = "/time2",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String json5() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        //1.如何让他不返回时间戳!所以我们要关闭它的时间戳功能
        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);
        //2.时间格式化问题!自定义日期格式对象;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //3.让mapper指定时间日期格式为SimpleDateFormat;
        mapper.setDateFormat(format);

        //写一个日期对象
        Date date = new Date();

        return mapper.writeValueAsString(date);

    }

    //发现问题,重复代码太多,给他编写一个工具类

    @RequestMapping(value = "/time3",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String json6() throws JsonProcessingException {
        return JsonUtils.getJson(new Date());
    }

    @RequestMapping(value = "/time4",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String json7() throws JsonProcessingException {
        return JsonUtils.getJson(new Date(),"HH:mm:ss yyyy-MM-dd");
    }
}

JsonUtils(很有意思,封装)

package com.lb.utils;

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

import java.text.DateFormat;
import java.text.SimpleDateFormat;

public class JsonUtils {

    //重载
    //如果传入一个参数,就调用默认的格式
    public static String getJson(Object object){
        return getJson(object,"yyyy-MM-dd HH:mm:ss");
    }

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

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

    }
}

结果:
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

后面两个用的是自定义工具类:
在这里插入图片描述

在这里插入图片描述

上面都是用的@ResponseBody注解,它就是把后台的对象转换成json字符串,返回到页面,和他对应的当然就是@RequestBody,一般用来负责接受前台的json数据,把json数据自动分装到pojo中;在之后Ajax来测试这一块。这两个注解一般都会在异步获取数据中使用到;

举报

相关推荐

学习json

AJAX和JSON的学习

Json和Ajax的学习

JavaWeb学习——JSON

学习记录:JSON

Python学习---JSON学习180130

0 条评论