做一次面向對象的體操:將 JSON 字符串轉換爲嵌套對象的一種方法

try { getPropertyUtils().getPropertyDescriptor(target, name); return; // Skip this property setter try { getPropertyUtils().getPropertyDescriptor(target, name); return; // Skip this property setter

public static String decapitalize(String name) {
if (name == null || name.length() == 0) {
return name;
}

if (name.length() > 1 && Character.isUpperCase(name.charAt(1)) &&
Character.isUpperCase(name.charAt(0))){
return name;
}
char chars[] = name.toCharArray();
chars[0] = Character.toLowerCase(chars[0]);
return new String(chars);
}

這裡 name 是 getter/setter 方法的第四位開始的字符串。比如 gId 的 setter 方法為 setGId ,那麼 name = GId 。根據這個方法得到的 name = GId ,也就是走到中間那個 if 分支了。 之所以這樣,方法的解釋是這樣的:

This normally means converting the first
* character from upper case to lower case, but in the (unusual) special
* case when there is more than one character and both the first and
* second characters are upper case, we leave it alone.
*
* Thus "FooBah" becomes "fooBah" and "X" becomes "x", but "URL" stays
* as "URL".

真相大白! 當使用 BeanUtils.populate 將 map 轉為對象時,對象的屬性命名要尤其注意: 第二個字母不能是大寫!

收工!

小結

本文展示了一種方法, 將具有內在關聯性的JSON字符串轉成對應的嵌套對象。 當處理複雜業務關聯的數據時,相比過程式的思維,轉換為對象的視角會更容易處理和使用。

關注我:私信回覆“666”獲取往期Java高級架構資料、源碼、筆記、視頻Dubbo、Redis、Netty、zookeeper、Spring cloud、分佈式、高併發等架構技術


分享到:


相關文章: