1 package com.ls.utils; 2 3 import java.lang.reflect.Array; 4 import java.lang.reflect.Field; 5 import java.util.Arrays; 6 7 /** 8 * @author Lartimes 9 * @version 1.0 10 * @description: JSON工具类 11 * toJSONString 12 * parseObject 13 * @since 2023/10/24 16:50 14 */ 15 public class JSON { 16 private JSON() { 17 } 18 19 20 /** 21 * toJsonString 22 * @param obj 23 * @return 24 */ 25 public static String toJSONString(Object obj) { 26 if (ClassUtiils.isPrimitiveTypeOrWrapper(obj.getClass())) { 27 throw new RuntimeException("the method of toJsonString only support complex Object"); 28 } 29 StringBuilder builder = new StringBuilder(); 30 Class<?> aClass = obj.getClass(); 31 builder.append("{"); 32 Field[] declaredFields = aClass.getDeclaredFields(); 33 try { 34 for (Field field : declaredFields) { 35 field.setAccessible(true); 36 String key = field.getName(); 37 Object value = field.get(obj); 38 if (value == null) { //优先级最高 39 builder.append("\"" + key + "\" : "); 40 builder.append((String) null); 41 builder.append(","); 42 } else if (Number.class.isAssignableFrom(value.getClass())) { //是Number 43 builder.append("\"" + key + "\" : "); 44 builder.append(value); 45 builder.append(","); 46 } else if (Boolean.class.isAssignableFrom(value.getClass())) { //如果是booleaan 47 builder.append("\"" + key + "\" : "); 48 builder.append(value); 49 builder.append(","); 50 } else if (String.class.isAssignableFrom(value.getClass())) { 51 builder.append("\"" + key + "\" : "); 52 builder.append("\"" + value + "\""); 53 builder.append(","); 54 } else if (value.getClass().isArray()) { 55 if (ClassUtiils.isPrimitiveTypeOrWrapper(value.getClass().componentType())) { 56 throw new RuntimeException("the " + field.getName() + "should not be primitiveType arrays"); 57 } 58 builder.append("["); 59 for (int i = 0; i < Array.getLength(value); i++) { 60 Object o = Array.get(value, i); 61 builder.append(toJSONString(o)); 62 } 63 builder.deleteCharAt(builder.length() - 1); 64 builder.append("],"); 65 } else if (!ClassUtiils.isPrimitiveTypeOrWrapper(value.getClass())) { 66 builder.append("\"" + key + "\" : "); 67 builder.append(toJSONString(value)); 68 builder.append(","); 69 } 70 /* * null "key" : null 71 number 优先级 "key" : number 72 true /false "key" : true/false 73 string "key" : "value" 74 * array "key" : [递归] 75 * object "key" : {"key..."} 递归 76 * */ 77 } 78 } catch (Exception e) { 79 e.printStackTrace(); 80 } 81 builder.deleteCharAt(builder.length() - 1); 82 builder.append("}"); 83 return builder.toString(); 84 } 85 86 public static <T> T parseObject(String jsonStr, Class<T> clazz) { 87 88 if (ClassUtiils.isPrimitiveTypeOrWrapper(clazz)) { 89 throw new RuntimeException("the method of toJsonString only support complex Object"); 90 } 91 Field[] fields = clazz.getDeclaredFields(); 92 T t = null; 93 try { 94 t = clazz.getDeclaredConstructor().newInstance(); 95 for (Field field : fields) { 96 field.setAccessible(true); 97 String name = field.getName(); 98 Class<?> fieldType = field.getType(); 99 /* * null "key" : null 1 100 number 优先级 "key" : number 101 true /false "key" : true/false 102 string "key" : "value" 2 103 * array "key" : [递归] 3 104 * object "key" : {"key..."} 递归 4 105 */ 106 if (Number.class.isAssignableFrom(fieldType) || Boolean.class.isAssignableFrom(fieldType)) { //是Number或者Boolean 107 int index = jsonStr.indexOf(name); 108 int begin = jsonStr.indexOf(":", index + 1); 109 int end = jsonStr.indexOf(",", begin); 110 if (end == -1) { //---- 说明是最后一个 找到 } trim即可 111 end = jsonStr.indexOf("}", begin); 112 } 113 String value = jsonStr.substring(begin + 1, end).trim(); 114 if (!ClassUtiils.primitiveWrapperTypeMap.containsKey(fieldType)) {//包装类 115 fieldType = ClassUtiils.getPrimitiveType(fieldType); 116 } 117 Object invoked = fieldType.getDeclaredMethod("valueOf", String.class).invoke(null, value); 118 field.set(t, invoked); 119 System.out.println(invoked + "注入成功"); 120 } else if (String.class.isAssignableFrom(fieldType)) { 121 System.out.println(name); 122 int index = jsonStr.indexOf(name); 123 int begin = getStringIndex(jsonStr, index + 1); 124 int end = jsonStr.indexOf("\"", begin); 125 String value = jsonStr.substring(begin, end); 126 field.set(t, value); 127 System.out.println("注入成功" + value); 128 System.out.println("str"); 129 } else if (fieldType.isArray()) { 130 // 获取内部基本属性 , 如果是complex Object 继续否则,error 131 Class<?> componentType = fieldType.componentType(); 132 if (ClassUtiils.isPrimitiveTypeOrWrapper(componentType)) { 133 throw new RuntimeException("the " + field.getName() + "should not be primitiveType arrays"); 134 } 135 int index = jsonStr.indexOf(name); 136 int begin = jsonStr.indexOf("[", index + 1); 137 int end = getEndIndex(jsonStr.substring(begin)); 138 String value = jsonStr.substring(begin, end); 139 Object[] objects = new Object[getArrayLength(value)]; 140 for (int i = 0; i < objects.length; i++) { 141 objects[i] = parseObject(getComponentStr(value, i + 1), componentType); 142 } 143 field.set(t, objects); 144 System.out.println("注入成功" + Arrays.toString(objects)); 145 } else if (!ClassUtiils.isPrimitiveTypeOrWrapper(fieldType)) { 146 // 如果是obj 147 int index = jsonStr.indexOf(name); 148 int begin = jsonStr.indexOf("{", index + 1); 149 150 String value = getObjectEnd(jsonStr.substring(begin)); 151 System.out.println(value); 152 field.set(t, parseObject(value, fieldType)); 153 System.out.println("诸如成功" + value); 154 } 155 } 156 } catch (Exception e) { 157 e.printStackTrace(); 158 } 159 System.out.println(t); 160 return t; 161 } 162 163 164 private static String getComponentStr(String value, int sequence) { 165 String retStr = null; 166 int begin = 0; 167 int end = 0; 168 for (int i = 0; i < sequence; i++) { 169 begin = value.indexOf("{"); 170 end = value.indexOf("}", begin); 171 int countL = 0; 172 int countR = 1; 173 for (int j = begin; j < end; j++) { 174 if (value.charAt(j) == '{') { 175 countL++; 176 } 177 } 178 while (countR != countL) { 179 end = value.indexOf("}", end); 180 countR++; 181 } 182 retStr = value.substring(begin, end + 1); 183 value = value.substring(end + 1); 184 } 185 return retStr; 186 } 187 188 private static int getEndIndex(String substring) { 189 int countA = 0; 190 int countB = 0; 191 for (int i = 0; i < substring.length(); i++) { 192 if (substring.charAt(i) == '[') { 193 countA++; 194 } else if (substring.charAt(i) == ']') { 195 countB++; 196 } 197 if (countB == countA) { 198 return countB + 1; 199 } 200 } 201 throw new RuntimeException("the format of this jsonStr is illegal "); 202 } 203 204 /** 205 * String类型获取其value “value” 第一个字母的值 206 * 207 * @param str 208 * @return 209 */ 210 211 private static int getStringIndex(String str, int beginIndex) { 212 int index = str.indexOf("\"", str.indexOf("\"", beginIndex) + 1) + 1; 213 return index; 214 } 215 216 217 /** 218 * @param str 219 * @return 220 */ 221 private static int getArrayLength(String str) { 222 // { {{}}}, { {{}}} ,{ {{}}} 从中找长度 223 int count = 0; 224 int begin = 0; 225 while ((begin = str.indexOf("{")) != -1) { 226 int end = str.indexOf("}"); 227 while (!countArray(str.substring(begin, end + 1))) { 228 end = str.indexOf("}", end + 1); 229 } 230 count++; 231 str = str.substring(end + 1); 232 } 233 return count; 234 } 235 236 private static boolean countArray(String pointCut) { 237 int countL = 0; 238 int countR = 0; 239 for (int i = 0; i < pointCut.length(); i++) { 240 if (pointCut.charAt(i) == '{') { 241 countL++; 242 } else if (pointCut.charAt(i) == '}') { 243 countR++; 244 } 245 } 246 return countL == countR; 247 } 248 249 private static String getObjectEnd(String str) { 250 System.out.println(str); 251 int countL = 0; 252 int countR = 0; 253 for (int i = 0; i < str.length(); i++) { 254 if (str.charAt(i) == '{') { 255 countL++; 256 } else if (str.charAt(i) == '}') { 257 countR++; 258 } 259 if (countL == countR) { 260 return str.substring(0, i + 1); 261 } 262 } 263 throw new RuntimeException("the format of this jsonStr is illegal "); 264 } 265 }
标签:end,String,int,builder,value,parseObject,JSON,utils,append From: https://www.cnblogs.com/lartimes/p/17878096.html