现在,我写了一种从键获取JSONObject数据的通用方法,如何将其更改为通用方法?现在,每次调用该方法时都必须更改类型。
String a= (String) ObdDeviceTool.getResultData(result, "a", String.class);
Double b= (Double) ObdDeviceTool.getResultData(result, "b", Double.class);
public static Object getJSONObjectData(JSONObject result,String key,Object type){
if (result.containsKey(key)) {
if(type.equals(String.class))
return result.getString(key);
if(type.equals(Double.class))
return result.getDouble(key);
if(type.equals(Long.class))
return result.getLong(key);
if(type.equals(Integer.class))
return result.getInt(key);
}
return null;
}
最佳答案
private static <T> T getJSONObjectData(JSONObject result, String key, Class<T> type)
{
Object value = result.get(key);
return type.cast(value);
}
您必须注意的是:
JSONException
中不存在key
,则result
将冒泡ClassCastException
与type
的实际类型不匹配,则value
将冒泡如有必要,请随意处理以上级别。