1.Json-lib
json-lib最开始的也是应用最广泛的json解析工具,json-lib 不好的地方确实是依赖于很多第三方包,包括commons-beanutils.jar,commons-collections.jar,commons-lang.jar,commons-logging.jar,ezmorph-1.0.6.jar,对于复杂类型的转换,json-lib对于json转换成bean还有缺陷,比如一个类里面会出现另一个类的list或者map集合,json-lib从json到bean的转换就会出现问题。json-lib在功能和性能上面都不能满足现在互联网化的需求。
2.Gson
Gson是目前功能最全的Json解析神器,Gson当初是为因应Google公司内部需求而由Google自行研发而来,但自从在2008年五月公开发布第一版后已被许多公司或用户应用。Gson的应用主要为toJson与fromJson两个转换函数,无依赖,不需要例外额外的jar,能够直接跑在JDK上。
而在使用这种对象转换之前需先创建好对象的类型以及其成员才能成功的将JSON字符串成功转换成相对应的对象。类里面只要有get和set方法,Gson完全可以将复杂类型的json到bean或bean到json的转换,是JSON解析的神器。
Gson在功能上面无可挑剔,但是性能上面比FastJson有所差距。
3.fastjson
Fastjson是一个Java语言编写的高性能的JSON处理器,由阿里巴巴公司开发。无依赖,不需要例外额外的jar,能够直接跑在JDK上。FastJson在复杂类型的Bean转换Json上会出现一些问题,可能会出现引用的类型,导致Json转换出错,需要制定引用。
FastJson采用独创的算法,将parse的速度提升到极致,超过所有json库。
4.jackJson
相比json-lib框架,Jackson所依赖的jar包较少,简单易用并且性能也要相对高些。而且Jackson社区相对比较活跃,更新速度也比较快。Jackson对于复杂类型的json转换bean会出现问题,一些集合Map,List的转换出现问题。Jackson对于复杂类型的bean转换Json,转换的json格式不是标准的Json格式。
相关maven依赖
<!--jsonLib-->
<!-- https://mvnrepository.com/artifact/net.sf.json-lib/json-lib -->
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.3</version>
<classifier>jdk15</classifier>
</dependency> <!--Gson-->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.3.1</version>
</dependency>
<!--fastJson-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.4</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency> <!--jackSon-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.0</version>
</dependency>
</dependencies>
1.Json-lib 使用方法
package com.jxufe.study.jsonstudy.test; import com.jxufe.study.jsonstudy.model.User;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.junit.Test; import java.util.*; public class JsonLibTest {
@Test
public void beanToJson()
{
User user = new User("zengting",25,new Date(),"1232456@qq.com");
JSONObject jsonObject = JSONObject.fromObject(user);
System.out.println(jsonObject.toString());
}
@Test
public void jsonToBean()
{
String json = "{\"age\":25,\"birthday\":{\"date\":7,\"day\":4,\"hours\":18,\"minutes\":7,\"month\":11,\"seconds\":23,\"time\":1512641243792,\"timezoneOffset\":-480,\"year\":117},\"email\":\"1232456@qq.com\",\"name\":\"zengting\"}\n";
JSONObject jsonObject = JSONObject.fromObject(json);
User user = (User) JSONObject.toBean(jsonObject,User.class);
System.out.println(user);
} @Test
public void listToJson()
{
List<User> usersList = new ArrayList<User>();
usersList.add(new User("zengting",23,new Date(),"3794411584@qq.com"));
usersList.add(new User("mindong",23,new Date(),"3794411584@qq.com"));
usersList.add(new User("liliang",21,new Date(),"3794411584@qq.com"));
String jsonString = JSONArray.fromObject(usersList).toString();
System.out.println(jsonString);
}
@Test
public void jsonToList()
{
List<User> usersList = new ArrayList<User>();
usersList.add(new User("zengting",23,null,"187021323@qq.com"));
usersList.add(new User("mindong",23,null,"3794411584@qq.com"));
String jsonString = JSONArray.fromObject(usersList).toString();
System.out.println(jsonString); JSONArray jsonArray = JSONArray.fromObject(jsonString);
List<User> list = JSONArray.toList(jsonArray, new User(),new JsonConfig());
for (User user : list) {
System.out.println(user);
}
}
@Test
public void JsonToArray() {
String jsonString = "[{\"age\":23,\"birthday\":null,\"email\":\"3794411584@qq.com\",\"name\":\"zengting\"},{\"age\":23,\"birthday\":null,\"email\":\"3794411584@qq.com\",\"name\":\"mindong\"}]";
JSONArray jsonArray = JSONArray.fromObject(jsonString);
Object[] obj = (Object[]) JSONArray.toArray(jsonArray, User.class);
for (int i = 0; i < obj.length; i++) {
System.out.println((User) obj[i]);
}
} // Map to Json
@Test
public void MapToJson() {
Map<String, User> map = new HashMap<String, User>();
map.put("person1", new User("zengting",23,null,"3794411584@qq.com"));
map.put("person2", new User("mindong",23,null,"3794411584@qq.com"));
String json = JSONObject.fromObject(map).toString();
System.out.println(json);
} // Json to map
@Test
public void JsonToMap() {
String jsonStr = "{\"person2\":{\"age\":23,\"birthday\":null,\"email\":\"3794411584@qq.com\",\"name\":\"mindong\"},\"person1\":{\"age\":23,\"birthday\":null,\"email\":\"3794411584@qq.com\",\"name\":\"zengting\"}}";
JSONObject jsonObject = JSONObject.fromObject(jsonStr);
Map<String,User> map = new HashMap<String,User>();
for (Iterator<?> iter = jsonObject.keys(); iter.hasNext();) {
String key = (String) iter.next();
map.put(key,(User)JSONObject.toBean((JSONObject) jsonObject.get(key),User.class));
}
for(String key : map.keySet()){
System.out.println((User)map.get(key));
}
}
}
2.Gson使用方法
package com.jxufe.study.jsonstudy.test; import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jxufe.study.jsonstudy.model.User;
import org.junit.Test; import java.lang.reflect.Type;
import java.util.*; public class GsonTest {
private Gson gson = new Gson();
@Test
public void jsonToBean()
{
String jsonStr = "{\"name\":\"zengting\",\"age\":23,\"birthday\":\"Dec 7, 2017 3:54:28 PM\",\"email\":\"3794411584@qq.com\"}";
User user = gson.fromJson(jsonStr,User.class);
System.out.println(user);
}
@Test
public void beanToJson()
{
User user = new User("zengting",23,new Date(),"3794411584@qq.com");
System.out.println(gson.toJson(user));
}
@Test
public void listToJson()
{
List<User> usersList = new ArrayList<User>();
usersList.add(new User("zengting",23,new Date(),"3794411584@qq.com"));
usersList.add(new User("mindong",23,new Date(),"3794411584@qq.com"));
usersList.add(new User("liliang",21,new Date(),"3794411584@qq.com")); System.out.println(gson.toJson(usersList));
}
@Test
public void jsonToList()
{
String jsonList = "[{\"name\":\"zengting\",\"age\":23,\"birthday\":\"Dec 7, 2017 4:00:58 PM\",\"email\":\"3794411584@qq.com\"},{\"name\":\"mindong\",\"age\":23,\"birthday\":\"Dec 7, 2017 4:00:58 PM\"," +
"\"email\":\"3794411584@qq.com\"},{\"name\":\"liliang\",\"age\":21,\"birthday\":\"Dec 7, 2017 4:00:58 PM\",\"email\":\"3794411584@qq.com\"}]"; Type type = new TypeToken<ArrayList<User>>() {
}.getType();
List<User> userList = gson.fromJson(jsonList,type);
System.out.println(userList); } @Test
public void mapToJson()
{
Map<Integer,User> userMap = new HashMap<Integer, User>();
userMap.put(1,new User("zengting",23,new Date(),"3794411584@qq.com"));
userMap.put(1,new User("mindong",22,new Date(),"3794411584@qq.com"));
userMap.put(1,new User("liliang",25,new Date(),"3794411584@qq.com"));
System.out.println(gson.toJson(userMap));
}
@Test
public void jsonToMap()
{
String json = "{\"1\":{\"name\":\"liliang\",\"age\":25,\"birthday\":\"Dec 7, 2017 4:05:56 PM\",\"email\":\"3794411584@qq.com\"}}\n";
Type type = new TypeToken<HashMap<Integer,User>>(){}.getType();
System.out.println(gson.fromJson(json,type));
}
@Test
public void listStringToJson()
{
List<String> strings = new ArrayList<String>();
strings.add("json");
strings.add("mindong");
strings.add("liliang");
System.out.println(gson.toJson(strings));
System.out.println(gson.toJson("zhenghong"));
} }
3.fastjson 使用
package com.jxufe.study.jsonstudy.test; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.jxufe.study.jsonstudy.model.User;
import org.junit.Test; import java.util.*; /**
* @author hong.zheng
* @Description
* @date 2017-12-07-16:14
**/
public class FastJsonTest {
@Test
public void beanToJson()
{
System.out.println(JSON.toJSON(new User("mindong",11,new Date(),"123")));
System.out.println(JSON.toJSON("zhenghong"));
}
@Test
public void jsonToBean()
{
String jsonStr = "{\"birthday\":1512634693590,\"name\":\"mindong\",\"age\":11,\"email\":\"123\",\"testName\":\"Today is 2017-12-07\"}\n";
System.out.println(JSON.parseObject(jsonStr,User.class));
}
@Test
public void testJsonToList()
{
List<User> usersList = new ArrayList<User>();
usersList.add(new User("zengting",23,new Date(),"12312312312@qq.com"));
usersList.add(new User("mindong",23,new Date(),"12312312312@qq.com"));
usersList.add(new User("liliang",21,new Date(),"12312312312@qq.com"));
JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd";
String jsonList = JSON.toJSONString(usersList, SerializerFeature.WriteDateUseDateFormat);
System.out.println(jsonList); System.out.println("------------------------------------------------------------------");
List<User> list = JSON.parseArray(jsonList,User.class);
System.out.println(list); System.out.println("------------------------------------------------------------------");
System.out.println( JSON.parseObject(jsonList,new TypeReference<List<User>>(){}));
} @Test
public void testMapToJson()
{
Map<Integer,User> userMap = new HashMap<Integer, User>();
userMap.put(1,new User("zengting",23,new Date(),"12345678@qq.com"));
userMap.put(2,new User("mindong",22,new Date(),"12345678@qq.com"));
userMap.put(3,new User("liliang",25,new Date(),"12345678@qq.com"));
String jsonMap = JSON.toJSONString(userMap);
System.out.println(jsonMap); Map<Integer,User> fromJsonMap = JSON.parseObject(jsonMap,new TypeReference<Map<Integer, User>>(){});
System.out.println(fromJsonMap);
} }
4.jackson-lib 使用
package com.jxufe.study.jsonstudy.test; import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jxufe.study.jsonstudy.model.User;
import org.junit.Test; import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map; /**
* @author hong.zheng
* @Description
* @date 2017-12-08-9:29
**/
public class JacksonTest {
@Test
public void beanToJson() throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
//writeObject可以转换java对象,eg:JavaBean/Map/List/Array等
User user = new User("zengting",23,new Date(),"12345678@qq.com");
String jsonString = objectMapper.writeValueAsString(user);
System.out.println(jsonString);
}
@Test
public void jsonToBean () throws IOException {
ObjectMapper objectMapper = new ObjectMapper(); String jsonString = "{\"name\":\"zengting\",\"age\":23,\"birthday\":1512696816772,\"email\":\"12345678@qq.com\",\"1TestName\":\"Today is 2017-12-07\"}\n";
User user = objectMapper.readValue(jsonString, User.class);
System.out.println(user);
}
@Test
public void listToJson() throws IOException {
List<User> list = new ArrayList<User>();
list.add(new User("mindong",31,new Date(),"1321"));
list.add(new User("zengting",31,new Date(),"1321"));
list.add(new User("liliang",31,new Date(),"1321"));
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.writeValue(System.out,list); }
@Test
public void jsonTolist() throws IOException {
String json = "[{\"name\":\"mindong\",\"age\":31,\"birthday\":1512698926871,\"email\":\"1321\",\"1TestName\":\"Today is 2017-12-07\"},{\"name\":\"zengting\",\"age\":31,\"birthday\":1512698926871,\"email\":\"1321\",\"1TestName\":\"Today is 2017-12-07\"},{\"name\":\"liliang\",\"age\":31,\"birthday\":1512698926871,\"email\":\"1321\",\"1TestName\":\"Today is 2017-12-07\"}]";
ObjectMapper objectMapper = new ObjectMapper();
List<User> list = objectMapper.readValue(json ,List.class);
for (int i = 0; i <list.size() ; i++) {
User user = list.get(i); // 转化失败,List<User> 的值是List<LinkedHashMap<String,Object>>,LinkedHashMap<String,Object>不能转化为User
System.out.println(list.get(i));
}
}
@Test
public void jsonTolist1() throws IOException {
String json = "[{\"name\":\"mindong\",\"age\":31,\"birthday\":1512698926871,\"email\":\"1321\",\"1TestName\":\"Today is 2017-12-07\"},{\"name\":\"zengting\",\"age\":31,\"birthday\":1512698926871,\"email\":\"1321\",\"1TestName\":\"Today is 2017-12-07\"},{\"name\":\"liliang\",\"age\":31,\"birthday\":1512698926871,\"email\":\"1321\",\"1TestName\":\"Today is 2017-12-07\"}]";
ObjectMapper objectMapper = new ObjectMapper();
List<Map<String,Object>> list = objectMapper.readValue(json ,List.class);
for (int i = 0; i <list.size() ; i++) {
Map<String,Object> map = list.get(i);
String name = map.get("name").toString();
Integer age = Integer.valueOf(map.get("age").toString());
Date date = new Date(Long.valueOf(map.get("birthday").toString()));
String email = map.get("email").toString();
User user = new User(name,age,date,email);
System.out.println(user);
}
}
@Test
public void jsonToArray() throws IOException {
String json = "[{\"name\":\"mindong\",\"age\":31,\"birthday\":1512698926871,\"email\":\"1321\",\"1TestName\":\"Today is 2017-12-07\"},{\"name\":\"zengting\",\"age\":31,\"birthday\":1512698926871,\"email\":\"1321\",\"1TestName\":\"Today is 2017-12-07\"},{\"name\":\"liliang\",\"age\":31,\"birthday\":1512698926871,\"email\":\"1321\",\"1TestName\":\"Today is 2017-12-07\"}]";
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); User []users = objectMapper.readValue(json ,User[].class);
for (int i = 0; i <users.length ; i++) {
User user = users[i];
System.out.println(user.getClass());
System.out.println(users[i]);
}
} }
四种解析方式对Date类型的解析不太一样
package com.jxufe.study.jsonstudy.test; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import net.sf.json.JSONObject;
import org.junit.Test; import java.io.IOException;
import java.util.Date; /**
* @author hong.zheng
* @Description
* @date 2017-12-08-10:31
**/
public class DateCompare {
@Test
public void jsonLibDate()
{
JSONObject jsonObject = JSONObject.fromObject(new Date());
System.out.println(jsonObject.toString());
//输出 {"date":8,"day":5,"hours":11,"minutes":7,"month":11,"seconds":2,"time":1512702422553,"timezoneOffset":-480,"year":117} }
@Test
public void fastJsonDate()
{
System.out.println(JSON.toJSON(new Date()));
//输出 Fri Dec 08 11:07:14 CST 2017
JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd";
String jsonDate = JSON.toJSONString(new Date(), SerializerFeature.WriteDateUseDateFormat);
System.out.println(jsonDate);
//"2017-12-08"
}
@Test
public void GsonDate()
{
Gson gson = new Gson();
System.out.println(gson.toJson(new Date()));
//输出 "Dec 8, 2017 11:07:34 AM"
gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
System.out.println(gson.toJson(new Date()));
//输出 "2017-12-08" }
@Test
public void jacksonDate() throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.writeValue(System.out,new Date());
//输出 1512702466576 }
}
发现一个奇怪的解析结果,JsonLib 和 Jackson 会将以Get开头的方法解析成结果。
package com.jxufe.study.jsonstudy.test; import com.fasterxml.jackson.databind.ObjectMapper; import com.jxufe.study.jsonstudy.model.User;
import com.jxufe.study.jsonstudy.model.OtherBean; import net.sf.json.JSONObject;
import org.junit.Test; import java.io.IOException;
import java.util.Date; /**
* @author hong.zheng
* @Description
* @date 2017-12-08-11:26
**/
public class OtherJson {
@Test
public void jsonLibTest()
{
OtherBean otherBean = new OtherBean();
otherBean.setName("mindong");
JSONObject jsonObject = JSONObject.fromObject(otherBean);
System.out.println(jsonObject.toString());
//{"name":"mindong","otherName":"getMethod"} 会调用 以Get开头的方法,生成Json
}
@Test
public void jacksonTest() throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
OtherBean otherBean = new OtherBean();
otherBean.setName("xiaoting");
objectMapper.writeValue(System.out,otherBean);
// 输出 {"name":"xiaoting","otherName":"GetMethod"} 会调用 以Get开头的方法,生成Json
}
}
Bean如下
package com.jxufe.study.jsonstudy.model; /**
* @author hong.zheng
* @Description
* @date 2017-12-08-12:30
**/
public class OtherBean
{
private String name; public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} @Override
public String toString() {
return "OtherBean{" +
"name='" + name + '\'' +
'}';
} /**
* 以Get 开头,Bean 没有这个属性
* @return
*/
public String getOtherName()
{
return "getMethod";
}
}