JSON基础,传递JSON数据,介绍jackson、gson、fastjson、json-lib四种主流框架!

1、什么是JSON?

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。诞生于2002年。易于人阅读和编写。同时也易于机器解析和生成。JSON是目前主流的前后端数据传输方式。

JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C, C++, C#, Java, JavaScript, Perl, Python等)。 这些特性使JSON成为理想的数据交换语言。

几乎所有的APP、应用、网站、程序都离不开JSON。

2、JSON的数据结构?

  1. null:表示为 null
  2. boolean:表示为 true 或 false
  3. number:一般的浮点数表示方式
  4. string:表示为 "..."
  5. array:表示为 [ ... ]
  6. object:表示为 { ... }
  7. object(含array):表示为 {...[...]...}
  8. array(含object):表示为 [{...},{...},{...}...]

2.1  Object  (JSONObject)

以键值对的形式出现,key和value之间用“:”隔开,两个键值对之间用“,”隔开,一般表示形式如下:

{'key1':'value1','key2':'value2'};

例如:

{

"name":"LiMing",
"age":20,
"gender":"Male"
}

2.2  Array  (JSONArray)

跟Java中普通意义上的数组类似,一般形式如下:

['arr1','arr2','arr3'];

例如:

{
  "name": "Website",
  "num": 3,
  "sites": [ "Google.com", "Taobao.com", "163.com" ]
}

JSON数组的元素也可以是对象,例如:

{
"employees": [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName":"Jones" }
]
}

3、前端向后端发送JSON数据

开发环境:javascript,jQuery

思路:

第一步:将前端数据通过JSON.stringify()转化为JSON字符串,使用jQuery.ajax通过POST请求将JSON数据发送到后端服务器。

第二部:后端服务器成功接收并返回一个新的JSON字符串,前端通过JSON.parse()将JSON字符串转化为JSON对象。

<script type="text/javascript">
	//JSON.stringify()方法用于将JavaScript值转换为JSON字符串
	var jsonparams = JSON.stringify({"Parameters":[{"FULLCNAME":fullcname,"CONTYPE":contype,"DATE":date}]});
	jQuery.ajax({
		url:'******.url',
		type:'POST',
		dataType:'JSON',//设置返回值类型
		data:jsonparams,//传参,格式为JSON
		contentType:'application/json;charset=UTF-8',//设置传递参数类型
		async:false,//同步请求
		cache:false,
		success:function(jsondata){
			//将jsondata转化为json对象
			var jsonobject = JSON.parse(jsondata);
			var result = jsonobject.result;//结果
			var msg = jsonobject.msg;//结果信息
		}
	});
</script>

4、后端返回JSON数据

这里我们分别介绍jackson、gson、fastjson、json-lib四种主流框架。

开发环境:Spring-boot2+

1、Jackson:Spring-boot2中内置,开源,简单易用,只需添加最基础的Web依赖即可使用。

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

1.1我们创建一个Student实体类。

package com.example.demohelloworld.Json;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.util.Date;
public class Student {
    private String name;
    private Integer age;
    private String gender;
    //返回的json数据忽略该字段
    @JsonIgnore
    private String mobile;
    //返回json数据格式化
    @JsonFormat( pattern = "yyyy-MM-dd")
    private Date birthday;

    public String getName() {return name;}
    public void setName(String name) {this.name = name;}
    public Integer getAge() {return age;}
    public void setAge(Integer age) {this.age = age;}
    public String getGender() {return gender;}
    public void setGender(String gender) {this.gender = gender;}
    public String getMobile() {return mobile;}
    public void setMobile(String mobile) {this.mobile = mobile;}
    public Date getBirthday() {return birthday;}
    public void setBirthday(Date birthday) {this.birthday = birthday;}
}

1.2我们创建一个StudentController,返回student对象即可。

package com.example.demohelloworld.Json;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
@RestController
public class StudentController {
    @GetMapping(value = "/student",produces = "application/json;charset=utf-8")
    public Student student(){
        Student student=new Student();
        student.setName("XiaoMing");
        student.setAge(23);
        student.setGender("Male");
        student.setMobile("13977665544");
        student.setBirthday(new Date());
        return student;
    }
}

1.3我们启动项目,在浏览器中输入http://localhost:8080/student,即可以在网页中看到返回的JSON数据了。(也可以使用postman测试,选择get请求)。

总结:Jackson是Spring-boot自带的处理方式,采用这种方式,对于字段忽略、日期格式化等常见需求均可以通过注解来解决。

2、Gson:是目前功能最全的Json解析神器,由Google自行研发而来,主要包含toJson与fromJson两个转换函数。

在Spring-boot中使用Gson我们需要先除去默认的Jackson依赖,然后添加Gson依赖。

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>com.fasterxml.jackson.core</groupId>
                    <artifactId>jackson-databind</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
        </dependency>

2.1Spring-boot默认提供了Gson的自动转化类,可以像Jackson一样直接使用Gson,但如果需要对日期数据进行格式化、忽略字段等操作,那么还需要我们自定义GsonHttpMessageConverter类。

 注意:针对JSON返回数据需要忽略字段,我们设置修饰符为protected的字段被过滤掉。

package com.example.demohelloworld.Json;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.GsonHttpMessageConverter;
import java.lang.reflect.Modifier;

@Configuration
public class Gsonconfig {
    @Bean
    GsonHttpMessageConverter gsonHttpMessageConverter(){
        GsonHttpMessageConverter converter =new GsonHttpMessageConverter();
        GsonBuilder builder=new GsonBuilder();
        //设置日期格式
        builder.setDateFormat("yyyy-MM-dd");
        //忽略字段,Gson解析时,修饰符为protected的字段被过滤掉
        builder.excludeFieldsWithModifiers(Modifier.PROTECTED);
        Gson gson= builder.create();
        converter.setGson(gson);
        return converter;
    }
}

2.2我们将Student类中需要被忽略的字段改为protected。

package com.example.demohelloworld.Json;
import java.util.Date;
public class Student {
    private String name;
    private Integer age;
    private String gender;
    //Gson返回的json数据忽略该字段修改为protected
    protected String mobile;
    private Date birthday;

    public String getName() {return name;}
    public void setName(String name) {this.name = name;}
    public Integer getAge() {return age;}
    public void setAge(Integer age) {this.age = age;}
    public String getGender() {return gender;}
    public void setGender(String gender) {this.gender = gender;}
    public String getMobile() {return mobile;}
    public void setMobile(String mobile) {this.mobile = mobile;}
    public Date getBirthday() {return birthday;}
    public void setBirthday(Date birthday) {this.birthday = birthday;}
}

 2.3我们启动项目,在浏览器中输入http://localhost:8080/student,即可以在网页中看到返回的JSON数据了。(也可以使用postman测试,选择get请求)。

{"name":"XiaoMing","age":23,"gender":"Male","birthday":"2021-08-13"}

3、Fastjson:阿里巴巴开发的JSON处理框架,采用独创算法,是目前JSON解析速度最快的开源框架,少量配置即可使用非常方便。

同样,我们需要先除去默认的Jackson依赖,然后添加Fastjson依赖。

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>com.fasterxml.jackson.core</groupId>
                    <artifactId>jackson-databind</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.78</version>
        </dependency>

3.1要使用fastjson,我们需要先对fastjson进行配置:通过自定义MyFastJsonConfig,完成对FastJsonHttpMessageConverter的配置。

我们分别定义JSON解析过程中的日期格式、数据编码、是否生成JSON中输出类名、是否输出value为null的数据、生成的JSON格式化、空集合输出[]而非null、空字符串输出""而非null等,在下文代码中有详细的注释。

package com.example.demohelloworld.Json;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.nio.charset.StandardCharsets;
@Configuration
public class MyFastJsonConfig {
    @Bean
    FastJsonHttpMessageConverter fastjsonconfig() {
        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
        FastJsonConfig config = new FastJsonConfig();
        //设置日期格式
        config.setDateFormat("yyyy-MM-dd");
        //设置数据编码
        config.setCharset(StandardCharsets.UTF_8);
        config.setSerializerFeatures(
                //是否生成JSON中输出类名
                SerializerFeature.WriteClassName,
                //是否输出value为null的数据
                SerializerFeature.WriteMapNullValue,
                //生成的JSON格式化
                SerializerFeature.PrettyFormat,
                //空集合输出[]而非null
                SerializerFeature.WriteNullListAsEmpty,
                //空字符串输出""而非null等
                SerializerFeature.WriteNullStringAsEmpty
        );
        fastJsonHttpMessageConverter.setFastJsonConfig(config);
        return fastJsonHttpMessageConverter;
    }
}

3.2配置完成后,我们在application.properties中设置一下响应编码,避免出现JSON中文乱码,配置如下:

server.servlet.encoding.force-response=true

3.3我们启动项目,在浏览器中输入http://localhost:8080/student,即可以在网页中看到返回的JSON数据了。(也可以使用postman测试,选择get请求)。

总结:fastjson由阿里巴巴开发维护,功能强大,解析速度快,配置简单,推荐日常使用。 

4、Json-lib:是最开始应用也是应用最广泛的json解析工具,它需要较多第三方包,对复杂转换效果较差,在功能和性能上不太能满足现在互联网高速发展需求。

同样,我们需要先除去默认的Jackson依赖,然后添加json-lib依赖。这里需要指定JDK版本<classifier>jdk13/15</classifier>。

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>com.fasterxml.jackson.core</groupId>
                    <artifactId>jackson-databind</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
            <classifier>jdk13</classifier>
        </dependency>

4.1我们修改一下StudentController,返回JSONObject对象即可,原Student实体类不再使用。

package com.example.demohelloworld.Json;

import net.sf.json.JSONObject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
public class StudentController {
    @GetMapping(value = "/student",produces = "application/json;charset=utf-8")
    public JSONObject student(){
        //返回一个JSON对象
        JSONObject student =new JSONObject();
        student.put("name","小明");
        student.put("age",23);
        student.put("gender","Male");
        student.put("mobile","13977665544");
        student.put("birthday",new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        return student;
    }
}

4.2我们启动项目,在浏览器中输入http://localhost:8080/student,即可以在网页中看到返回的JSON对象了。(也可以使用postman测试,选择get请求)。

{"name":"小明","age":23,"gender":"Male","mobile":"13977665544","birthday":"2021-08-13"}

4.3我还可以修改代码,让其返回一个JSONArray数组。

package com.example.demohelloworld.Json;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
public class StudentController {
    @GetMapping(value = "/student",produces = "application/json;charset=utf-8")
    public JSONArray students(){
        //返回一个JSON数组
        JSONArray students =new JSONArray();
        JSONObject student1 =new JSONObject();
        student1.put("name","小明");
        student1.put("age",23);
        student1.put("gender","Male");
        student1.put("mobile","13977665544");
        student1.put("birthday",new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        JSONObject student2 =new JSONObject();
        student2.put("name","韩梅梅");
        student2.put("age",21);
        student2.put("gender","Female");
        student2.put("mobile","13788663344");
        student2.put("birthday",new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        students.add(student1);
        students.add(student2);
        return students;
    }
}

执行结果如下:

总结:json-lib可以用于练习和简单应用,在复杂开发和商业级应用中不推荐。

 5、四种框架性能总结

通过多方测试,JSON序列化性能FastJson>Jackson>Gson>Jsonlib。当序列化次数比较小的时候,Gson性能最好,当不断增加的时候到了100000,Gson明显弱于Jackson和FastJson,这时候FastJson性能表现最佳。另外还可以看到不管数量多少,Jackson表现都较为优异。而Json-lib表现较差。JSON反序列化测试,Gson、 Jackson和 FastJson区别不大,Json-lib表现较差。

 5、JSON应用总结

①无论前后端都需要使用JSON,而语法又有一定的差异,需要掌握常用的使用方法。

②大部分API接口都要使用JSON数据。

③JWT(JSON Web Tokens) 在单点登录中有广泛的应用。

④JSON简洁、方便,大有取代XML之势。

⑤数据交互首选JSON。

  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值