java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > json框架及Jackson返回结果

基于常用json框架介绍和Jackson返回结果处理方式

作者:M_Blood

这篇文章主要介绍了基于常用json框架介绍和Jackson返回结果处理方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

json框架介绍,Jackson返回结果处理

介绍常用json框架和注解的使用,自定义返回json结构和格式

1、常用框架 阿里 fastjson,谷歌gson等

JavaBean序列化为Json,性能:Jackson > FastJson > Gson > Json-lib 同个结构

Jackson、FastJson、Gson类库各有优点,各有自己的专长

空间换时间,时间换空间

2、jackson处理相关自动

实体类代码如下:

public class rData {
    
    @JsonIgnore
    private String code;
    @JsonProperty(value = "agenum")
    private int age;
    @JsonFormat(pattern="yyyy-MM-dd hh:mm:ss",locale="zh",timezone="GMT+8")
    private Date createDate;
    @JsonInclude(JsonInclude.Include.NON_NULL)
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Date getCreateDate() {
        return createDate;
    }
    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    
    public rData(String code, int age) {
        this.code = code;
        this.age = age;
    }
    public rData(String code, int age, Date createDate, String name) {
        this.code = code;
        this.age = age;
        this.createDate = createDate;
        this.name = name;
    }
}

测试类代码:

@RestController
public class HttpController {
    @GetMapping("/testjson")
    public Object param6(){
        return new rData("jackson",1,new Date(),"lion");
    }
}

结果:

{"createDate":"2018-09-18 09:36:31","name":"lion","agenum":1}

code被忽略了,所以不显示;age被别名代替"agenum"

使用jackson返回json数据

1、SpringMVC如何返回json数据

1.1、添加jar包

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

1.2、配置spring文件,添加mvc命名空间和约束等

 xmlns:mvc="http://www.springframework.org/schema/mvc"
  http://www.springframework.org/schema/mvc
  http://www.springframework.org/schema/mvc/spring-mvc.xsd
 <mvc:annotation-driven/>

1.3、方法上添加@ResponseBody

 @ResponseBody

2、例子

2.1、配置pom.xml

 <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.0.8.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>5.0.8.RELEASE</version>
    </dependency>
    <!-- Spring的核心工具包-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>5.0.8.RELEASE</version>
    </dependency>
    <!--在基础IOC功能上提供扩展服务,还提供许多企业级服务的支持,有邮件服务、任务调度、远程访问、缓存以及多种视图层框架的支持-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.0.8.RELEASE</version>
    </dependency>
    <!-- Spring IOC的基础实现,包含访问配置文件、创建和管理bean等 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>5.0.8.RELEASE</version>
    </dependency>
    <!-- Spring context的扩展支持,用于MVC方面 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>5.0.8.RELEASE</version>
    </dependency>
    <!-- Spring表达式语言 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-expression</artifactId>
      <version>5.0.8.RELEASE</version>
    </dependency>
    <!--springAop开发必须加入的包-->
    <dependency>
      <groupId>aopalliance</groupId>
      <artifactId>aopalliance</artifactId>
      <version>1.0</version>
    </dependency>
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.8.13</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>5.0.8.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>5.0.8.RELEASE</version>
    </dependency>
    <!--jackson返回json-->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.5</version>
    </dependency>
  </dependencies>

2.2、配置spring.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:p="http://www.springframework.org/schema/p"
       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
                           http://www.springframework.org/schema/context/spring-context.xsd
                            http://www.springframework.org/schema/mvc
                           http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!--扫描controller-->
    <context:component-scan base-package="com"></context:component-scan>
    <!--视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--jsp所在位置-->
        <property name="prefix" value="/"></property>
        <!--jsp文件后缀名-->
        <property name="suffix" value=".jsp"></property>
    </bean>
    <mvc:annotation-driven /> <!--注解驱动-->
</beans>

2.3、配置web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <servlet>
    <servlet-name>springMvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--加载spring配置文件,原来是通过 ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");-->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>springMvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <!--处理post乱码-->
  <filter>
    <filter-name>characterEncodingFilter</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>
  <filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

2.4、添加User实体类

package com.fan.entity;
import java.util.Arrays;
import java.util.Date;
public class User {
    private String username;
    private String password;
    private int[] box;
    private Date date;
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public int[] getBox() {
        return box;
    }
    public void setBox(int[] box) {
        this.box = box;
    }
    public Date getDate() {
        return date;
    }
    public void setDate(Date date) {
        this.date = date;
    }
    @Override
    public String toString() {
        return "User{" +
                "username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", box=" + Arrays.toString(box) +
                ", date=" + date +
                '}';
    }
}

2.5、 TestJsonController测试类

@Controller
public class TestJsonController {
     //http://localhost:8080/testjson1
    @RequestMapping("/testjson1")
    @ResponseBody //返回json字符串注解
    public User test(){
        User user=new User();
        user.setUsername("malijuan");
        user.setPassword("123");
        user.setBox(new int[]{1,2,3});
        user.setDate(new Date());
        return user;
    }
    //http://localhost:8080/testjson2
    @RequestMapping("/testjson2")
    @ResponseBody  //返回json字符串注解
    public List test2(){
        User user=new User();
        List list=new ArrayList();
        for(int i=0;i<5;i++){
            user.setUsername("malijuan");
            user.setPassword("123");
            user.setBox(new int[]{1,2,3});
            user.setDate(new Date());
            list.add(user);
        }
        return list;
    }
}

2.6、启动tomcat测试

测试1

测试2

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文