FastjsonUtils.java 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package com.uas.ps.message.util;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.JSONArray;
  4. import com.alibaba.fastjson.JSONObject;
  5. import com.alibaba.fastjson.parser.Feature;
  6. import com.alibaba.fastjson.serializer.SerializerFeature;
  7. import java.util.List;
  8. /**
  9. * alibaba fastjson工具类封装
  10. * @author yingp
  11. * @see JSON
  12. *
  13. */
  14. public class FastjsonUtils {
  15. public static Feature DEFAULT_PARSER_FEATURE = Feature.DisableCircularReferenceDetect;
  16. public static SerializerFeature DEFAULT_SERIAL_FEATURE = SerializerFeature.DisableCircularReferenceDetect;
  17. /**
  18. * 把JSON文本parse为JSONObject或者JSONArray
  19. *
  20. * @param text text
  21. * @return
  22. */
  23. public static Object parse(String text) {
  24. return JSON.parse(text, DEFAULT_PARSER_FEATURE);
  25. }
  26. /**
  27. * 把JSON文本parse成JSONObject
  28. *
  29. * @param text text
  30. * @return
  31. */
  32. public static final JSONObject parseObject(String text) {
  33. return JSON.parseObject(text, DEFAULT_PARSER_FEATURE);
  34. }
  35. /**
  36. * 把JSON文本parse为JavaBean
  37. *
  38. * @param text text
  39. * @param clazz clazz
  40. * @return
  41. */
  42. public static final <T> T fromJson(String text, Class<T> clazz) {
  43. return JSON.parseObject(text, clazz, DEFAULT_PARSER_FEATURE);
  44. }
  45. /**
  46. * 把JSON文本parse成JSONArray
  47. *
  48. * @param text text
  49. * @return
  50. */
  51. public static final JSONArray fromJsonArray(String text) {
  52. return JSON.parseArray(text);
  53. }
  54. /**
  55. * 把JSON文本parse成JavaBean集合
  56. *
  57. * @param text text
  58. * @param clazz clazz
  59. * @return
  60. */
  61. public static final <T> List<T> fromJsonArray(String text, Class<T> clazz) {
  62. return JSON.parseArray(text, clazz);
  63. }
  64. /**
  65. * 将JavaBean序列化为JSON文本
  66. *
  67. * @param object object
  68. * @return
  69. */
  70. public static final String toJson(Object object) {
  71. return JSON.toJSONString(object, DEFAULT_SERIAL_FEATURE);
  72. }
  73. /**
  74. * 将JavaBean转换为JSONObject或者JSONArray。
  75. *
  76. * @param javaObject javaObject
  77. * @return
  78. */
  79. public static final Object toObject(Object javaObject) {
  80. return JSON.toJSON(javaObject);
  81. }
  82. }