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\":\"[email protected]\"}"; User user = gson.fromJson(jsonStr,User.class); System.out.println(user); } @Test public void beanToJson() { User user = new User("zengting",23,new Date(),"[email protected]"); System.out.println(gson.toJson(user)); } @Test public void listToJson() { List<User> usersList = new ArrayList<User>(); usersList.add(new User("zengting",23,new Date(),"[email protected]")); usersList.add(new User("mindong",23,new Date(),"[email protected]")); usersList.add(new User("liliang",21,new Date(),"[email protected]")); 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\":\"[email protected]\"},{\"name\":\"mindong\",\"age\":23,\"birthday\":\"Dec 7, 2017 4:00:58 PM\"," + "\"email\":\"[email protected]\"},{\"name\":\"liliang\",\"age\":21,\"birthday\":\"Dec 7, 2017 4:00:58 PM\",\"email\":\"[email protected]\"}]"; 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(),"[email protected]")); userMap.put(1,new User("mindong",22,new Date(),"[email protected]")); userMap.put(1,new User("liliang",25,new Date(),"[email protected]")); 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\":\"[email protected]\"}}\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 使用