Gson 工具類

<code class=" hljs java">import java.util.List;java

02.import java.util.Map;json

03. google

04.import com.google.gson.Gson;spa

05.import com.google.gson.reflect.TypeToken;.net

06. code

07. get

08.public class GsonUtil {class

09.private static Gson gson = null;import

10.static {object

11.if (gson == null) {

12.gson = new Gson();

13.}

14.}

15. 

16.private GsonUtil() {

17.}

18. 

19./**

20.* 轉成json

21.*

22.* @param object

23.* @return

24.*/

25.public static String GsonString(Object object) {

26.String gsonString = null;

27.if (gson != null) {

28.gsonString = gson.toJson(object);

29.}

30.return gsonString;

31.}

32. 

33./**

34.* 轉成bean

35.*

36.* @param gsonString

37.* @param cls

38.* @return

39.*/

40.public static <T> T GsonToBean(String gsonString, Class<T> cls) {

41.T t = null;

42.if (gson != null) {

43.t = gson.fromJson(gsonString, cls);

44.}

45.return t;

46.}

47. 

48./**

49.* 轉成list

50.*

51.* @param gsonString

52.* @param cls

53.* @return

54.*/

55.public static <T> List<T> GsonToList(String gsonString, Class<T> cls) {

56.List<T> list = null;

57.if (gson != null) {

58.list = gson.fromJson(gsonString, new TypeToken<List<T>>() {

59.}.getType());

60.}

61.return list;

62.}

63. 

64./**

65.* 轉成list中有map的

66.*

67.* @param gsonString

68.* @return

69.*/

70.public static <T> List<Map<String, T>> GsonToListMaps(String gsonString) {

71.List<Map<String, T>> list = null;

72.if (gson != null) {

73.list = gson.fromJson(gsonString,

74.new TypeToken<List<Map<String, T>>>() {

75.}.getType());

76.}

77.return list;

78.}

79. 

80./**

81.* 轉成map的

82.*

83.* @param gsonString

84.* @return

85.*/

86.public static <T> Map<String, T> GsonToMaps(String gsonString) {

87.Map<String, T> map = null;

88.if (gson != null) {

89.map = gson.fromJson(gsonString, new TypeToken<Map<String, T>>() {

90.}.getType());

91.}

92.return map;

93.}</code>

相關文章
相關標籤/搜索