JsonUtils.java 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package thyyxxk.webserver.utils;
  2. import com.alibaba.fastjson.JSONArray;
  3. import com.alibaba.fastjson.JSONObject;
  4. import java.util.Map;
  5. /**
  6. * json工具类
  7. *
  8. * @Version 1.0
  9. */
  10. public final class JsonUtils {
  11. /**
  12. * 去除json值前后空格
  13. *
  14. * @param jsonStr jsonStr
  15. * @return
  16. */
  17. public static JSONObject jsonTrim(String jsonStr) {
  18. return jsonTrim(JSONObject.parseObject(jsonStr));
  19. }
  20. public static String jsonTrimToString(String jsonStr) {
  21. return jsonTrim(JSONObject.parseObject(jsonStr)).toJSONString();
  22. }
  23. /**
  24. * 去除value的空格
  25. *
  26. * @param jsonObject jsonObject
  27. */
  28. public static JSONObject jsonTrim(JSONObject jsonObject) {
  29. for (Map.Entry<String, Object> next : jsonObject.entrySet()) {
  30. Object value = next.getValue();
  31. if (value != null) {
  32. if (value instanceof String) {
  33. //清空值前后空格
  34. jsonObject.put(next.getKey(), ((String) value).trim());
  35. } else if (value instanceof JSONObject) {
  36. jsonTrim((JSONObject) value);
  37. } else if (value instanceof JSONArray) {
  38. jsonTrimArray((JSONArray) value);
  39. }
  40. }
  41. }
  42. return jsonObject;
  43. }
  44. /**
  45. * 清空JSONArray 值前后空格
  46. *
  47. */
  48. private static void jsonTrimArray(JSONArray array) {
  49. if (array != null && !array.isEmpty()) {
  50. for (int i = 0; i < array.size(); i++) {
  51. Object object = array.get(i);
  52. if (object != null) {
  53. if (object instanceof String) {
  54. array.set(i, ((String) object).trim());
  55. } else if (object instanceof JSONObject) {
  56. jsonTrim((JSONObject) object);
  57. } else if (object instanceof JSONArray) {
  58. jsonTrimArray((JSONArray) object);
  59. }
  60. }
  61. }
  62. }
  63. }
  64. }