2016-08-09 2 views
6

지금 나는 지금 내가 메서드를 호출 할 때 유형마다 시간을 변경해야? 일반적인 방법으로 변경하는 key.How에서 된 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; 
} 
+0

@ JonnyHenly 시도해 보았지만 변경할 수 없습니다. public static T getJSONObjectData (JSONObject 결과, String 키, T 유형) – flower

답변

3
private static <T> T getJSONObjectData(JSONObject result, String key, Class<T> type) 
{ 
    Object value = result.get(key); 
    return type.cast(value); 
} 

당신은 알고 있어야하는 것 : type 실제 유형과 일치하지 않는 경우

  • key 경우 JSONException 의지 거품이 result
  • 가까 ClassCastException 의지 거품에 존재하지 않는 value

위의 레벨을 자유롭게 처리 할 수 ​​있습니다. 필요한 경우 . 조금 더 @Spotted하여 답을 촬영

+0

키 값이 0이면 result.getDouble (key) 괜찮습니다.하지만 더블. 캐스트 (0)가 잘못되었습니다. – flower

+0

@flower 당신이 옳습니다. 그러나 나는 최선의 접근 방식이 그것을 해결하는 것이 무엇인지 모르겠다. 그 값을'Number'로 받아 들일 수 있습니까? 그렇지 않으면이 값을 double로 검색한다는 것을 안다면'0.0' 삽입에주의해야합니다. – Spotted

+0

예, 0을 반환하지만 이중 값을 반환하는 경우에는 길을 사용할 수 없습니다. 데모에서 오래된 방법을 사용합니다. – flower

1

JSONObject에는 개체를 반환하는 메서드가 있습니다.

Integer i = (Integer) result.get("integerKey"); 
String s = (String) result.get("stringKey"); 
Double d = (Double) result.get("doubleKey"); 

은 JSONObject 개체입니다.

2

, 나는 전략 패턴을 사용하고 같은 것을 할 거라고 :

private static final Map<Class<?>, BiFunction<JSONObject, String, Object>> converterMap = 
    initializeMap(); 

private static Map<Class<?>, BiFunction<JSONObject, String, Object>> initializeMap() { 
    Map<Class<?>, BiFunction<JSONObject,String, Object>> map = new HashMap<>(); 
    map.put(String.class, (jsonObject, key) -> jsonObject.getString(key)); 
    map.put(Integer.class, (jsonObject, key) -> jsonObject.getInt(key)); 
    // etc. 
    return Collections.unmodifiableMap(map); 
} 

private static <T> Optional<T> getJSONObjectData(JSONObject json, String key, Class<T> type) { 

    return 
    Optional.ofNullable(converterMap.get(key)) 
    .map(bifi -> bifi.apply(json, key)) 
    .map(type::cast); 
} 

지금 당신은 키가 대상 유형 컨버터의지도를 가지고 있습니다. 형식에 맞는 변환기가 있으면이 변환기가 사용되며 개체가 올바른 형식으로 반환됩니다. 그렇지 않으면 Optional.empty()가 반환됩니다.
Consider typesafe heterogeneous containers :


Effective Java (2nd Edition) 항목 29의 응용 프로그램입니다.

+0

안전한 주조를 위해이 답변을 좋아하지만 컴파일되지 않습니다. 당신은 교체해야'지도 <..., 기능 <...>>''지도 <..., BiFunction <...>>'와'converterMap.get (유형)'와'(키) converterMap.get'와. – Spotted

+0

@ 예, 이전 버전에서 리팩토링하여 한 곳을 놓쳤습니다. 감사 –

관련 문제