从速度模板中的 Hashmap 通过键获取特定值

get particular value by key from Hashmap in velocity template

我有一个 java 代码如下

  public static void main(String args[]) throws Exception {
    VelocityEngine engine = new VelocityEngine();
    engine.init();

    Template template = engine.getTemplate("userinfo.vm");

    VelocityContext vc = new VelocityContext();

    Map<String, Object> jsonResponse = new HashMap<String, Object>();

    jsonResponse.put("44", "United Kingdom");
    jsonResponse.put("33", "France");
    jsonResponse.put("49", null);

    vc.put("userList", jsonResponse);
    StringWriter writer = new StringWriter();
    template.merge(vc, writer);

    System.out.println(writer);
}

在 .vm 文件中

#foreach ($mapEntry in $userList.entrySet())
$!{mapEntry.get("44")}
#end

我在这里尝试使用上面的代码获取特定值,但它没有给出预期的输出

我的预期输出是

 United Kingdom

使用此代码遍历您的地图值。它与您的几乎相同,但请注意:$userList.keySet() 而不是 $userList.entrySet()$!{userList.get($mapKey )} 而不是 $!{mapEntry.get("44")}

#foreach($mapKey in $userList.keySet())
    $!{userList.get($mapKey )}
#end

如果您只想访问地图的特定值,试试这个:

$!{userList.get("44")}

对于https://velocity.apache.org/engine/1.7/user-guide.html#set

You could access the first element above using $monkey.Map.get("banana") to return a String 'good', or even $monkey.Map.banana to return the same value.

对于https://velocity.apache.org/engine/1.7/user-guide.html#index-notation

$foo["bar"] ## Passing a string where $foo may be a Map