JSONUtil.java 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package com.uas.utils;
  2. import java.util.ArrayList;
  3. import java.util.HashMap;
  4. import java.util.List;
  5. import java.util.Map;
  6. import java.util.regex.Matcher;
  7. import java.util.regex.Pattern;
  8. public class JSONUtil {
  9. static final String Unicode_Pattern = "(\\\\u(\\p{XDigit}{4}))";
  10. public static String decodeUnicode(String jsonStr) {
  11. if (jsonStr != null) {
  12. // unicode格式的转化成汉字
  13. Pattern pattern = Pattern.compile(Unicode_Pattern);
  14. Matcher matcher = pattern.matcher(jsonStr);
  15. char ch;
  16. while (matcher.find()) {
  17. ch = (char) Integer.parseInt(matcher.group(2), 16);
  18. jsonStr = jsonStr.replace(matcher.group(1), ch + "");
  19. }
  20. }
  21. return jsonStr;
  22. }
  23. public static Map<Object, Object> toMap(String jsonStr) {
  24. jsonStr = decodeUnicode(jsonStr);
  25. jsonStr = jsonStr.substring(jsonStr.indexOf("{") + 1, jsonStr.lastIndexOf("}"));
  26. String[] strs;
  27. if(jsonStr.indexOf("\",\"")>0) strs = jsonStr.split(",\"");
  28. else strs = jsonStr.split(","); //字段名前没有引号的jsonStr ,类似bom校验:{bo_version:"V1.0",bo_mothercode:"BS00012",bo_ispast:"否",}
  29. String field = null;
  30. String value = null;
  31. Map<Object, Object> map = new HashMap<Object, Object>();
  32. for (String str : strs) {
  33. if (str.indexOf(":") > 0) {
  34. field = str.substring(0, str.indexOf(":"));
  35. if (field != null) {
  36. if (field.startsWith("\"")) {
  37. field = field.substring(1, field.length());
  38. }
  39. if (field.endsWith("\"")) {
  40. field = field.substring(0, field.lastIndexOf("\""));
  41. }
  42. }
  43. value = str.substring(str.indexOf(":") + 1);
  44. if (value != null) {
  45. if (value.startsWith("\"")) {
  46. value = value.substring(1, value.length());
  47. }
  48. if (value.endsWith("\"")) {
  49. value = value.substring(0, value.lastIndexOf("\""));
  50. }
  51. }
  52. map.put(field, value);
  53. }
  54. }
  55. return map;
  56. }
  57. public static List<Map<Object, Object>> toMapList(String jsonStr) {
  58. if (jsonStr != null) {
  59. if (jsonStr.startsWith("[")) {
  60. jsonStr = jsonStr.substring(1, jsonStr.length());
  61. }
  62. if (jsonStr.endsWith("]")) {
  63. jsonStr = jsonStr.substring(0, jsonStr.lastIndexOf("]"));
  64. }
  65. List<Map<Object, Object>> list = new ArrayList<Map<Object, Object>>();
  66. if (jsonStr.indexOf("},") > -1) {
  67. String[] js = jsonStr.split("},");
  68. for (String j : js) {
  69. if (!j.endsWith("}"))
  70. j = j + "}";
  71. list.add(toMap(j));
  72. }
  73. } else if (jsonStr.indexOf("{") > -1 && jsonStr.indexOf("}") > -1) {
  74. list.add(toMap(jsonStr));
  75. }
  76. return list;
  77. }
  78. return null;
  79. }
  80. }