Now I write a common way to get the JSONObject data from a key.How to change it to a generic method?Now I have to change the type every time when I call the method.
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);
}
What you must be aware of:
JSONException
will bubble up if key
doesn't exist in result
ClassCastException
will bubble up if type
doesn't match the real type of value
Feel free to handle these a level above if necessary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With