1. 什么是json
什么是 JSON ?
JSON 指的是 JavaScript 对象表示法(JavaScript Object Notation)
JSON 是轻量级的文本数据交换格式
JSON 独立于语言 *
JSON 具有自我描述性,更易理解
2. 好多json类库
我们在java编程中用到json的时候会经常引入json类库,我们进行简单的罗列
2.1 json-lib
项目地址:http://json-lib.sourceforge.net/index.html
(1)pom文件
<!-- https://mvnrepository.com/artifact/net.sf.json-lib/json-lib -->
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
(2)示例
/**
* 将对象序列化成json字符串
* @param obj
* @return
*/
public static String bean2Json(Object obj){
JSONObject jsonObject=JSONObject.fromObject(obj);
return jsonObject.toString();
}
/**
* 将json字符串反序列化为对象
* @param jsonStr
* @param objClass 反序列化为该类的对象
* @return
*/
@SuppressWarnings("unchecked")
public static <T> T json2Bean(String jsonStr,Class<T> objClass){
return (T)JSONObject.toBean(JSONObject.fromObject(jsonStr), objClass);
}
2.2 org.json
(1)pom文件
<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180813</version>
</dependency>
2.3 gson
项目地址:https://github.com/google/gson
(1)pom文件
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
2.4 fastjson
项目地址:https://github.com/alibaba/fastjson
(1)pom文件
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.56</version>
</dependency>
2.5 jackson
项目地址:https://github.com/FasterXML/jackson
(1)pom文件
<!-- 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>