2017-09-11 19 views
0

키를 알 수없는 경우 JSON을 String으로 매핑 할 수 있습니까? 여기에 JSON 나는 API 얻을되어 다음과 같이Spring : JSON 키를 알 수 없을 때 JSON을 String으로 매핑

{ 
    "key1.abc": "Some translation", 
    "key2.abc": "Some other translation", 
... 
} 

내가 시도 :

ResponseEntity<String> responseEntity = restTemplate.exchange(uri, HttpMethod.GET, requestEntity, String.class); 

를하지만 오류로 인해 실패 :

JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token 

어떤 아이디어? 고마워요

+0

왜 당신이 문자열해야합니까를? – rorschach

답변

0
JSONObject json= searchResult.getJSONObject("json"); 
Iterator keys = json.keys(); 

while(keys.hasNext()) { 
    // loop to get the dynamic key 
    String currentDynamicKey = (String)keys.next(); 

    // get the value of the dynamic key 
    JSONObject currentDynamicValue = questionMark.getJSONObject(currentDynamicKey); 

    // do something here with the value... 
} 
+0

질문은 제공된 JSON에서 키를 찾는 것이 아니라 Spring'RestTemplate # exchange' 메소드를 사용할 때 수정하는 방법에 관한 것입니다. Java 객체로 deserialize를 시도합니다. – belgoros

1

마지막으로 다음과 같은 해결책이 있습니다.

{ 
    "some.translation.key": "traslated text", 
    "other.translation.key": "other traslated text" 
} 

Jackson 파서는 문자열이 아니라 매핑 할 대상으로 간주하지 않습니다. 그래서 응답을지도에 매핑해야했습니다. 는이를 달성하기 위해, 내가지도 유형의 ParameterizedTypeReference을 정의했다 :

ParameterizedTypeReference<Map<String, String>> typeRef = new ParameterizedTypeReference<Map<String, String>>() {}; 

그런 다음 exchange 방법에 전달 :

엔티티가 HttpEntity<Object> 클래스의 인스턴스
restTemplate.exchange(uri, HttpMethod.GET, requestEntity, typeRef); 

.

지도에 저장된 모든 번역을 갖는, 그것은 해당 키 알고 번역을 쉽게 얻을 수 있습니다 :

map.get("some.translation.key");