PageRenderTime 5551ms CodeModel.GetById 41ms RepoModel.GetById 2ms app.codeStats 0ms

/src/main/java/com/tts/util/JsonUtil.java

https://gitlab.com/Fish-Potato/TTStreet-core
Java | 80 lines | 65 code | 12 blank | 3 comment | 9 complexity | ab3552ce7807ed48a67514bd6849ad19 MD5 | raw file
  1. package com.tts.util;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.JSONObject;
  4. import com.alibaba.fastjson.parser.Feature;
  5. import com.alibaba.fastjson.parser.ParserConfig;
  6. import com.alibaba.fastjson.parser.deserializer.ParseProcess;
  7. import java.util.HashSet;
  8. import java.util.Set;
  9. /**
  10. * Created by tts on 2016/4/28.
  11. */
  12. public class JsonUtil {
  13. private static final Set<Object> clazzSet = new HashSet<Object>(){{add(String.class);add(Integer.class);add(Boolean.class);add(Long.class);add(Short.class);}};
  14. public static String toString(Object o) {
  15. if (o instanceof String ) {
  16. return (String) o;
  17. }
  18. return JSON.toJSONString(o);
  19. }
  20. @SuppressWarnings("unchecked")
  21. public static <T> T toObject(String param,Class<T> clazz) {
  22. T t = null;
  23. if(isSimpleType(clazz)) {
  24. return handlerSimpleType(param,clazz);
  25. } else {
  26. t = toObject(param, clazz,new Feature[0]);
  27. }
  28. return t;
  29. }
  30. public static <T> T toObject(String param,Class<T> clazz,Feature... features) {
  31. T t = null;
  32. if(isSimpleType(clazz)) {
  33. return handlerSimpleType(param,clazz);
  34. } else {
  35. t = toObject(param, clazz, ParserConfig.getGlobalInstance(), JSON.DEFAULT_PARSER_FEATURE, new Feature[0]);
  36. }
  37. return t;
  38. }
  39. public static <T> T toObject(String param, Class<T> clazz, ParserConfig config, int featureValues,
  40. Feature... features) {
  41. T t = null;
  42. if(isSimpleType(clazz)) {
  43. return handlerSimpleType(param,clazz);
  44. } else {
  45. t = toObject(param, clazz, ParserConfig.getGlobalInstance(), null, JSON.DEFAULT_PARSER_FEATURE, features);
  46. }
  47. return t;
  48. }
  49. public static <T> T toObject(String param, Class<T> clazz, ParserConfig config, ParseProcess processor,
  50. int featureValues, Feature... features) {
  51. T t = null;
  52. if(isSimpleType(clazz)) {
  53. return handlerSimpleType(param,clazz);
  54. } else {
  55. t = JSON.parseObject(param, clazz, config, processor, featureValues, features);
  56. }
  57. return t;
  58. }
  59. @SuppressWarnings("unchecked")
  60. private static <T> T handlerSimpleType(String param, Class<T> clazz) {
  61. T t = null;
  62. JSONObject jsonObject =(JSONObject) JSON.parse(param);
  63. return (T)jsonObject.get(jsonObject.keySet().iterator().next());
  64. }
  65. private static <T> boolean isSimpleType(Class<T> clazz) {
  66. return clazzSet.contains(clazz);
  67. }
  68. }