json物件和java物件的相互轉換方法(json-lib、jackson、fastjson、gson)
一 使用json-lib包下的JSONObject和JSONArray轉換
程式碼如下:
package com.test.test; import java.util.ArrayList; import java.util.List; import com.cn.entity.User; import net.sf.json.JSONArray; import net.sf.json.JSONObject; /** * JSONObject和JSONArray * @author sun.kai * 2016年8月7日 */ public class TestJsonOne { public static void main(String[] args){ long time1 = System.currentTimeMillis(); // Map<String, Object> param = new HashMap<String,Object>(); // param.put("id", 1); // param.put("userName", "admin管理員"); // param.put("password", "admin123456"); // param.put("age", 25); // JSONObject jsonObject = JSONObject.fromObject(param); // System.out.println(jsonObject); // JSONArray jsonArray = JSONArray.fromObject(param); // System.out.println(jsonArray); List<User> list = new ArrayList<User>(); User user1 = new User(); user1.setId(1); user1.setUserName("admin管理員"); user1.setPassword("admin123456"); user1.setAge(25); testJsonObject(user1); list.add(user1); User user2 = new User(); user2.setId(2); user2.setUserName("海角七號"); user2.setPassword("海角七號123456"); user2.setAge(26); list.add(user2); testJsonArray(list); long time2 = System.currentTimeMillis(); System.out.println(time2-time1); } @SuppressWarnings("static-access") public static void testJsonObject(User user){ System.out.println("JSONObject測試"); /* * java物件轉換成json物件 */ JSONObject jsonObject1 = JSONObject.fromObject(user); /* * json物件轉成字串 */ String jsonsString1 = jsonObject1.toString(); System.out.println(jsonObject1); System.out.println(jsonsString1); String jsonString2 = "{\"age\":25,\"id\":1,\"password\":\"admin123456\",\"userName\":\"admin管理員\"}"; /* * 字串轉成json物件 */ JSONObject jsonObject2 = JSONObject.fromObject(jsonString2); /* * json物件轉成java物件 */ User user2 = (User) jsonObject2.toBean(jsonObject2,User.class); System.out.println(user2.getUserName()); /* * 獲取json物件中的json物件陣列 */ String jsonString3 = "{\"abc\":[{\"age\":25,\"id\":1,\"password\":\"admin123456\",\"userName\":\"admin管理員\"}," + "{\"age\":26,\"id\":2,\"password\":\"海角七號123456\",\"userName\":\"海角七號\"}" + "]}"; //字串轉成json物件 JSONObject jsonObject3 = JSONObject.fromObject(jsonString3); //獲取json物件中的json物件陣列 JSONArray jsonArray = jsonObject3.getJSONArray("abc"); System.out.println(jsonArray.toString()); } @SuppressWarnings("unchecked") public static void testJsonArray(List<User> userList){ System.out.println("JSONArray測試"); /* * java物件列表轉換為json物件陣列 */ JSONArray jsonArray1 = JSONArray.fromObject(userList); /* * json物件陣列轉成字串 */ String arrayString1 = jsonArray1.toString(); System.out.println(jsonArray1); System.out.println(arrayString1); String arrayString2 = "[{\"age\":25,\"id\":1,\"password\":\"admin123456\",\"userName\":\"admin管理員\"},{\"age\":26,\"id\":2,\"password\":\"海角七號123456\",\"userName\":\"海角七號\"}]"; /* * 字串轉成json物件陣列 */ JSONArray jsonArray2 = JSONArray.fromObject(arrayString2); /* * json物件陣列轉成java物件 */ List<User> users = (List<User>) JSONArray.toCollection(jsonArray2, User.class); for(User user : users){ System.out.println(user.getUserName()); } /* * 迴圈json物件陣列,獲取json物件 */ for(int i = 0;i<jsonArray2.size();i++){ JSONObject jsonObject = jsonArray2.getJSONObject(i); System.out.println(jsonObject); } } }
User實體類程式碼:
執行後的結果:package com.cn.entity; import java.io.Serializable; public class User implements Serializable{ private static final long serialVersionUID = -154635138564326678L; private Integer id; private String userName; private String password; private Integer age; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName == null ? null : userName.trim(); } public String getPassword() { return password; } public void setPassword(String password) { this.password = password == null ? null : password.trim(); } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
JSONObject測試
{"age":25,"id":1,"password":"admin123456","userName":"admin管理員"}
{"age":25,"id":1,"password":"admin123456","userName":"admin管理員"}
admin管理員
[{"age":25,"id":1,"password":"admin123456","userName":"admin管理員"},{"age":26,"id":2,"password":"海角七號123456","userName":"海角七號"}]
JSONArray測試
[{"age":25,"id":1,"password":"admin123456","userName":"admin管理員"},{"age":26,"id":2,"password":"海角七號123456","userName":"海角七號"}]
[{"age":25,"id":1,"password":"admin123456","userName":"admin管理員"},{"age":26,"id":2,"password":"海角七號123456","userName":"海角七號"}]
admin管理員
海角七號
{"age":25,"id":1,"password":"admin123456","userName":"admin管理員"}
{"age":26,"id":2,"password":"海角七號123456","userName":"海角七號"}
686
二 使用jackson-databind包下的ObjectMapper
程式碼如下:
package com.test.test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.cn.entity.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* jackson是spring mvc內建的json轉換工具
* @author sun.kai
* 2016年8月7日
*/
public class TestJsonTwo {
public static void main(String[] args) throws JsonProcessingException{
long time1 = System.currentTimeMillis();
List<User> users = new ArrayList<User>();
User user1 = new User();
user1.setId(1);
user1.setUserName("admin管理員");
user1.setPassword("admin123456");
user1.setAge(25);
users.add(user1);
User user2 = new User();
user2.setId(2);
user2.setUserName("海角七號");
user2.setPassword("海角七號123456");
user2.setAge(26);
users.add(user2);
try {
testObjectMapper(users);
} catch (IOException e) {
e.printStackTrace();
}
long time2 = System.currentTimeMillis();
System.out.println(time2-time1);
}
public static void testObjectMapper(List<User> users) throws IOException{
ObjectMapper mapper = new ObjectMapper();
/*
* java物件是一個集合
* 轉成的字串是json物件陣列
*/
String mapperString1 = mapper.writeValueAsString(users);
System.out.println(mapperString1);
/*
* java物件不是一個集合
* 轉成json物件字串
*/
String mapperString2 = mapper.writeValueAsString(users.get(0));
System.out.println(mapperString2);
/*
* json物件陣列字串轉java物件集合
*/
String jsonString1 = "[{\"age\":25,\"id\":1,\"password\":\"admin123456\",\"userName\":\"admin管理員\"},{\"age\":26,\"id\":2,\"password\":\"海角七號123456\",\"userName\":\"海角七號\"}]";
User[] userArray = mapper.readValue(jsonString1, User[].class);
List<User> userList = Arrays.asList(userArray);
for (User user : userList) {
System.out.println(user.getUserName());
}
/*
* json物件字串轉java物件
*/
String jsonString2 = "{\"age\":25,\"id\":1,\"password\":\"admin123456\",\"userName\":\"admin管理員\"}";
User user = mapper.readValue(jsonString2, User.class);
System.out.println(user.getUserName());
}
}
執行後的結果:
[{"id":1,"userName":"admin管理員","password":"admin123456","age":25},{"id":2,"userName":"海角七號","password":"海角七號123456","age":26}]
{"id":1,"userName":"admin管理員","password":"admin123456","age":25}
admin管理員
海角七號
admin管理員
784
三 使用fastjson
程式碼如下:
package com.test.test;
import com.cn.entity.User;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
/**
* fastjson是阿里做的國有開源Java工具包
* @author sun.kai
* 2016年8月7日
*/
public class TestJsonThree {
public static void main(String[] args){
long time1 = System.currentTimeMillis();
List<User> users = new ArrayList<User>();
User user1 = new User();
user1.setId(1);
user1.setUserName("admin管理員");
user1.setPassword("admin123456");
user1.setAge(25);
users.add(user1);
User user2 = new User();
user2.setId(2);
user2.setUserName("海角七號");
user2.setPassword("海角七號123456");
user2.setAge(26);
users.add(user2);
testFastjson(users);
long time2 = System.currentTimeMillis();
System.out.println(time2-time1);
}
@SuppressWarnings("unchecked")
public static void testFastjson(List<User> users){
/*
* java物件是一個集合
* 轉成的字串是json物件陣列
*/
String fastjsonString1 = JSON.toJSONString(users);
System.out.println(fastjsonString1);
/*
* java物件不是一個集合
* 轉成json物件字串
*/
String fastjsonString2 = JSON.toJSONString(users.get(0));
System.out.println(fastjsonString2);
/*
* json物件陣列字串轉java物件集合
*/
String jsonString1 = "[{\"age\":25,\"id\":1,\"password\":\"admin123456\",\"userName\":\"admin管理員\"},{\"age\":26,\"id\":2,\"password\":\"海角七號123456\",\"userName\":\"海角七號\"}]";
List<User> userList = JSON.parseArray(jsonString1, User.class);
for (User user : userList) {
System.out.println(user.getUserName());
}
/*
* json物件陣列字串轉Map集合
*/
List<Map<String, Object>> maps = JSON.parseObject(jsonString1,new TypeReference<List<Map<String,Object>>>(){});
System.out.println(maps);
for (Map<String, Object> map : maps) {
System.out.println(map.get("userName"));
}
/*
* json物件字串轉java物件
*/
String jsonString2 = "{\"age\":25,\"id\":1,\"password\":\"admin123456\",\"userName\":\"admin管理員\"}";
User user = JSON.parseObject(jsonString2, User.class);
System.out.println(user.getUserName());
/*
* json物件字串轉Map
*/
Map<String, Object> map = JSON.parseObject(jsonString2, Map.class);
System.out.println(map);
System.out.println(map.get("userName"));
}
}
執行結果:
[{"age":25,"id":1,"password":"admin123456","userName":"admin管理員"},{"age":26,"id":2,"password":"海角七號123456","userName":"海角七號"}]
{"age":25,"id":1,"password":"admin123456","userName":"admin管理員"}
admin管理員
海角七號
[{id=1, age=25, userName=admin管理員, password=admin123456}, {id=2, age=26, userName=海角七號, password=海角七號123456}]
admin管理員
海角七號
admin管理員
{id=1, age=25, userName=admin管理員, password=admin123456}
admin管理員
338
四 使用Google的Gson
程式碼如下:
package com.test.test;
import com.cn.entity.User;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* google的gson
* https://mvnrepository.com/artifact/com.google.code.gson/gson
* @author sun.kai
* 2016年8月7日
*/
public class TestJsonFour {
public static void main(String[] args){
long time1 = System.currentTimeMillis();
List<User> users = new ArrayList<User>();
User user1 = new User();
user1.setId(1);
user1.setUserName("admin管理員");
user1.setPassword("admin123456");
user1.setAge(25);
users.add(user1);
User user2 = new User();
user2.setId(2);
user2.setUserName("海角七號");
user2.setPassword("海角七號123456");
user2.setAge(26);
users.add(user2);
testGson(users);
long time2 = System.currentTimeMillis();
System.out.println(time2-time1);
}
@SuppressWarnings("unchecked")
public static void testGson(List<User> users){
/*
* 建立Gson物件
*/
Gson gson = new Gson();
/*
* 獲得泛型引數的型別
*/
java.lang.reflect.Type type = new TypeToken<List<User>>() {}.getType();
/*
* java物件是一個集合
* 轉成的字串是json物件陣列
*/
String gsonString1 = gson.toJson(users);
System.out.println(gsonString1);
/*
* java物件不是一個集合
* 轉成json物件字串
*/
String gsonString2 = gson.toJson(users.get(0));
System.out.println(gsonString2);
/*
* json物件陣列字串轉java物件集合
*/
String jsonString1 = "[{\"age\":25,\"id\":1,\"password\":\"admin123456\",\"userName\":\"admin管理員\"},{\"age\":26,\"id\":2,\"password\":\"海角七號123456\",\"userName\":\"海角七號\"}]";
List<User> userList = gson.fromJson(jsonString1, type);
for (User user : userList) {
System.out.println(user.getUserName());
}
/*
* json物件陣列字串轉Map集合
*/
List<Map<String, Object>> maps = gson.fromJson(jsonString1,new TypeToken<List<Map<String, Object>>>() {}.getType());
System.out.println(maps);
for (Map<String, Object> map : maps) {
System.out.println(map.get("userName"));
}
/*
* json物件字串轉java物件
*/
String jsonString2 = "{\"age\":25,\"id\":1,\"password\":\"admin123456\",\"userName\":\"admin管理員\"}";
User user = gson.fromJson(jsonString2, User.class);
System.out.println(user.getUserName());
/*
* json物件字串轉Map
*/
Map<String, Object> map = gson.fromJson(jsonString2, Map.class);
System.out.println(map);
System.out.println(map.get("userName"));
}
}
執行結果:
[{"id":1,"userName":"admin管理員","password":"admin123456","age":25},{"id":2,"userName":"海角七號","password":"海角七號123456","age":26}]
{"id":1,"userName":"admin管理員","password":"admin123456","age":25}
admin管理員
海角七號
[{age=25.0, id=1.0, password=admin123456, userName=admin管理員}, {age=26.0, id=2.0, password=海角七號123456, userName=海角七號}]
admin管理員
海角七號
admin管理員
{age=25.0, id=1.0, password=admin123456, userName=admin管理員}
admin管理員
336