现在,我写了一种从键获取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将冒泡
  • 如果ClassCastExceptiontype的实际类型不匹配,则value将冒泡

    如有必要,请随意处理以上级别。

  • 07-24 09:43
    查看更多