Mustache-Java: How to get value in Map by key

空扰寡人 提交于 2020-01-05 04:00:20

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!