问题
I am using JMustache in Java.
I have Map variable in my Mustache template. How can I fetch a value at a particular key in the map, as we do in Java (map.get()).
I know how to iterate through keys and values of a Map in a template. But I want a solution without iteration so that I can evaluate an expression such as:
Data
{
"cities": [
{
"Tokyo": {
"overview": {
"population": "19000000",
"area": "450000"
}
}
},
{
"Sydney": {
"overview": {
"population": "4500000",
"area": "6250000"
}
}
}
]
}
Template
"The population of Tokyo is: {{cities['Tokyo'].overview.population}}"
回答1:
First, there is an issue with your mustache syntax. cities['Tokyo']
is not valid. cities
is an array. You can iterate over an array, but not select an element based on its key value (or any other condition for that matter).
So this JSON object fits better:
{
"cities": {
"Tokyo": {
"overview": {
"population": "19000000",
"area": "450000"
}
},
"Sydney": {
"overview": {
"population": "4500000",
"area": "6250000"
}
}
}
}
Second, you have to parse the JSON String
to a structure using Map
and List
objects. Most JSON parsers are able to do this. In this example, I use noggit.
@Test
public void testSO_45787572() throws IOException {
final String json =
"{\n" +
" \"cities\": {\n" +
" \"Tokyo\": {\n" +
" \"overview\": {\n" +
" \"population\": \"19000000\",\n" +
" \"area\": \"450000\"\n" +
" }\n" +
" },\n" +
" \"Sydney\": {\n" +
" \"overview\": {\n" +
" \"population\": \"4500000\",\n" +
" \"area\": \"6250000\"\n" +
" }\n" +
" }\n" +
" }\n" +
"}";
assertEquals("The population of Tokyo is: 19000000", Mustache.compiler()
.compile(new StringReader("The population of Tokyo is: {{cities.Tokyo.overview.population}}"))
.execute(new ObjectBuilder(new JSONParser(json)).getObject())
);
}
来源:https://stackoverflow.com/questions/45787572/mustache-java-how-to-get-value-in-map-by-key