Reputation: 3908
Is it possible to map a JSON to a String if its keys are unknown ? Here is a JSON I get for API:
{
"key1.abc": "Some translation",
"key2.abc": "Some other translation",
...
}
I tried as follows:
ResponseEntity<String> responseEntity = restTemplate.exchange(uri, HttpMethod.GET, requestEntity, String.class);
but it failed with error:
JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token
Any ideas ? Thank you
Upvotes: 0
Views: 2032
Reputation: 3908
Finally, the solution I came to is the following. When I get a response in this form:
{
"some.translation.key": "traslated text",
"other.translation.key": "other traslated text"
}
Jackson parser never considers it to be a String but an Object to map to. That's why I had to map the response to a Map.
To achieve this, I had to define ParameterizedTypeReference
of Map type:
ParameterizedTypeReference<Map<String, String>> typeRef = new ParameterizedTypeReference<Map<String, String>>() {};
Then pass it in to the exchange
method:
restTemplate.exchange(uri, HttpMethod.GET, requestEntity, typeRef);
where entity is an instance of HttpEntity<Object>
class.
Having all the translations saved in the Map, it is easy to get a translation knowing the corresponding key:
map.get("some.translation.key");
Upvotes: 2
Reputation:
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...
}
Upvotes: 0