Object轉JSON,子類讀父類內容

public class ObjectUtil {

	/**
	 * 從父類對類中讀數據
	 * @param parent
	 * @param subObj
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static void readDataFromParent(Object parent, Object subObj){
		Class parrentClazz = parent.getClass();
		Method[] methods = parrentClazz.getMethods();
		try{
			for(Method method : methods){
				if(method.getName().startsWith("get") && !method.getName().startsWith("getClass")){
					Object value = method.invoke(parent);
					String setName = method.getName().replaceFirst("g", "s");
					Method subSetMethod = parrentClazz.getMethod(setName, method.getReturnType());
					subSetMethod.invoke(subObj, value);
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	@SuppressWarnings({ "rawtypes" })
	public static JSONObject obj2Json(Object obj){
		if(obj == null){
			return null;
		}
		Class parrentClazz = obj.getClass();
		JSONObject ret = new JSONObject();
		Method[] methods = parrentClazz.getMethods();
		try{
			for(Method method : methods){
				if(method.getName().startsWith("get") && !method.getName().startsWith("getClass")){
					Object value = method.invoke(obj);
					if(value == null){
						continue;
					}
					String attrName = method.getName().substring("get".length());
					attrName = StringUtil.firstCharLower(attrName);
					if(isBasicType(value)){
						ret.put(attrName, value);
					}
					else if(value instanceof List){
						List list = (List)value;
						if(list != null){
							JSONArray ja = new JSONArray();
							for(Object varObj : list){
								if(!isBasicType(varObj)){
									ja.add(obj2Json(varObj));
								}
								else{
									ja.add(varObj);
								}
							}
							ret.put(attrName, ja);
						}
					}
					else{
						ret.put(attrName, obj2Json(value));
					}
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return ret;
	}
	
	
	/**
	 * 判斷是否是基礎類型對象,我把String也當作了基礎類型
	 * @param value
	 * @return
	 */
	private static boolean isBasicType(Object value){
		if(value.getClass() == int.class || value instanceof Integer){
			return true;
		}
		else if(value.getClass() == long.class || value instanceof Long){
			return true;
		}
		else if(value.getClass() == short.class || value instanceof Short){
			return true;
		}
		else if(value.getClass() == byte.class || value instanceof Byte){
			return true;
		}
		else if(value.getClass() == boolean.class || value instanceof Boolean){
			return true;
		}
		else if(value.getClass() == double.class || value instanceof Double){
			return true;
		}
		else if(value.getClass() == float.class || value instanceof Float){
			return true;
		}
		else if(value.getClass() == char.class || value instanceof Character){
			return true;
		}
		else if(value instanceof String){
			return true;
		}
		return false;
	}
}

發佈了35 篇原創文章 · 獲贊 15 · 訪問量 19萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章