JSON数据处理

发布时间:2024年01月09日

1.添加json依赖

springmvc 默认使用jackson作为json类库,不需要修改applicationContext-servlet.xml任何配置,只需引入以下类库springmvc就可以处理json数据:

<!--spring-json依赖-->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.0</version>
</dependency>

2.注解

  • @RequestBody:作用是接收前端ajax传递给后端的json字符串,并将json格式的数据转为java对象

  • @ResponseBody:作用是将java对象转为json格式的数据传递给前台ajax

3.JSON、集合、对象三种数据处理

3.1.JSON数据处理

1)pojo

package com.by.pojo;



import java.io.Serializable;
import java.util.Date;

public class Account implements Serializable {
    private Integer id;
    private String name;
    private Float money;
    private Address address;
    private Date date;


    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                ", address=" + address +
                ", date=" + date +
                '}';
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public Float getMoney() {
        return money;
    }

    public void setMoney(Float money) {
        this.money = money;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }
}
package com.by.pojo;

import java.io.Serializable;

public class Address implements Serializable {
    private String provinceName;
    private String cityName;
    


    @Override
    public String toString() {
        return "Address{" +
                "provinceName='" + provinceName + '\'' +
                ", cityName='" + cityName + '\'' +
                '}';
    }

    public String getProvinceName() {
        return provinceName;
    }

    public void setProvinceName(String provinceName) {
        this.provinceName = provinceName;
    }

    public String getCityName() {
        return cityName;
    }

    public void setCityName(String cityName) {
        this.cityName = cityName;
    }
}

2)编写controller层

@Controller
@RequestMapping("/Account")
public class AccountController {
@RequestMapping("/controller16")
    @ResponseBody //pojo---》转JSON
    public Account controller16(@RequestBody Account account){//@RequestBody json--》转pojo
        System.out.println(account);
        return account;
    }
}

3)在index.jsp里面定义ajax请求

添加按钮

 <input type="button" value="测试ajax请求json和响应json" id="testJson"/>

引入js库文件

<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>

编写ajax代码

  <script type="text/javascript">
    $(function(){
      $("#testJson").click(function(){
        $.ajax({
          type:"post",
          url:"/Account/controller16",
          contentType:"application/json;charset=UTF-8",
          data:'{"id":1,"name":"张二狗","money":999.0}',
          success:function(data) {
                     }
        })
      });
    })
  </script>

结果:

3.2集合数据处理?

1)编写controller层

@RequestMapping("/controller17")
    @ResponseBody
    public Map controller17(@RequestBody Account account){
       Map<String, Object> map = new HashMap<>();
        try {
            //int a=6/0;
            map.put("status",200);
            map.put("msg",account);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("status",500);
            map.put("msg","未知异常!!!!");
        }
        return map;
    }

2)编写ajax代码

<script type="text/javascript">
    $(function(){
      $("#testJson").click(function(){
        $.ajax({
          type:"post",
          url:"/Account/controller17",
          contentType:"application/json;charset=UTF-8",
          data:'{"id":1,"name":"张二狗","money":999.0}',
          success:function(data) {
            if (data.status == 200) {
              alert(data.msg.name);
              alert(data.msg.money);
            }else {
              alert(data.msg);
            }
          }
        })
      });
    })
  </script>

测试:

3.3对象数据处理

1)pojo

package com.by.pojo;

public class Result {
    private Integer status;
    private Object msg;

    @Override
    public String toString() {
        return "Result{" +
                "status=" + status +
                ", msg=" + msg +
                '}';
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public Object getMsg() {
        return msg;
    }

    public void setMsg(Object msg) {
        this.msg = msg;
    }
}

2)编写controller层

 @RequestMapping("/controller18")
    @ResponseBody
    public Result controller18(@RequestBody Account account){
        Result result = new Result();
        try {
            //int a=6/0;
            result.setStatus(200);
            result.setMsg(account);
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus(500);
            result.setMsg("未知异常!!!!!");
        }
        return result;
    }

3)编写ajax代码

 <script type="text/javascript">
    $(function(){
      $("#testJson").click(function(){
        $.ajax({
          type:"post",
          url:"/Account/controller18",
          contentType:"application/json;charset=UTF-8",
          data:'{"id":1,"name":"张二狗","money":999.0}',
          success:function(data) {
            if (data.status == 200) {
              alert(data.msg.name);
              alert(data.msg.money);
            }else {
              alert(data.msg);
            }
          }
        })
      });
    })
  </script>

结果:

文章来源:https://blog.csdn.net/qq_62965575/article/details/135488910
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。