java 对象转json,java首字母小写,判断方法是否为javabean方法
生活随笔
收集整理的這篇文章主要介紹了
java 对象转json,java首字母小写,判断方法是否为javabean方法
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
將java對象轉(zhuǎn)成json可用的類庫很多,知名的有fastjson,jackson等,今天在做項(xiàng)目的時候發(fā)現(xiàn)項(xiàng)目沒有上述依賴,用的是google的gson,因此封裝方法將java對象轉(zhuǎn)成gson代表的json對象。
大致流程如下:
1:通過反射獲取java對象的所有public方法,再篩選出javabean的getter方法(方法返回類型為boolean 則為is開頭)。
2:遍歷篩選出的方法,通過 字符串首字母小寫方法 從方法名計(jì)算得到對應(yīng)的屬性名。
3:通過目標(biāo)對象調(diào)用篩選出的方法,將屬性名與方法返回值添加到j(luò)son中。
以下是代碼實(shí)現(xiàn):
1:判斷方法是否為javabean的getter方法:
public static boolean isJavaBeanGetterMethod(Method method){if (method == null || method.getParameterCount() > 0 || "void".equals( method.getReturnType().getName() )) return false;String methodName = method.getName();if ("getClass".equals(methodName)) return false;boolean isReturnBoolean = "boolean".equals( method.getReturnType().getName() );if (methodName.matches("^(get[A-Z])[a-zA-Z0-9_$]+") && !isReturnBoolean|| methodName.matches("^(is[A-Z])[a-zA-Z0-9_$]+") && isReturnBoolean){return true;}return false;}2:通過Javabean方法獲取對應(yīng)的屬性名+字符串首字母小寫+判斷字符串是否有內(nèi)容
/*** @description:通過Javabean方法獲取對應(yīng)的屬性名* @param method* @return java.lang.String*/public static String getJavaBeanFieldName(Method method){String methodName = method.getName();String fieldName = methodName.replaceFirst("^(get|is|set)", "");return initialLower(fieldName);}/*** @description:首字母小寫* @param str* @return java.lang.String*/public static String initialLower(String str){if (isEmpty(str)) return str;char[] strChar = str.toCharArray();if (strChar[0] >= 'A' && strChar[0] <= 'Z'){strChar[0] += 32;return new String(strChar);}return str;}/*** @description:判斷字符串是否有內(nèi)容* @param str* @return boolean*/public static boolean isEmpty(String str){return str == null || "".equals( str.trim() );}3:對象轉(zhuǎn)成json
/*** @description:對象轉(zhuǎn)jsonObject* @param obj* @param addNotNull 是否只處理非空屬性* @param ignoreFields 忽略的屬性* @exception IllegalAccessException* @return com.google.gson.JsonObject*/public static JsonObject objectToJson(Object obj, boolean addNotNull, String...ignoreFields) throws Exception {if (obj == null) return null;List<String> ignoreFieldList = Arrays.asList(ignoreFields);JsonObject rsJson = new JsonObject();Class cls = obj.getClass();//拿public方法Method[] methods = cls.getMethods();for (Method method : methods) {if (Modifier.isStatic( method.getModifiers() ) || !isJavaBeanGetterMethod(method)) continue;Object value = method.invoke(obj);if (value == null && addNotNull) continue;String fieldName = getJavaBeanFieldName(method);if (ignoreFieldList.contains(fieldName)) continue;rsJson.addProperty(fieldName, String.valueOf(value));}return rsJson;}調(diào)用運(yùn)行結(jié)果:
?
總結(jié)
以上是生活随笔為你收集整理的java 对象转json,java首字母小写,判断方法是否为javabean方法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: js文件中加载其他js文件
- 下一篇: mysql同时查出符合条件数据与总数