简体   繁体   English

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

[英]get particular value by key from Hashmap in velocity template

i have a java code like below我有一个像下面这样的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);
}

in .vm file在 .vm 文件中

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

Here i am trying to get particular value using above code, but its not giving expected output在这里,我试图使用上面的代码获得特定的价值,但它没有给出预期的输出

My expected output is我的预期输出是

 United Kingdom

Use this code to iterate through your map values.使用此代码迭代您的地图值。 It is almost the same as yours however pay attention to: $userList.keySet() instead of $userList.entrySet() and $!{userList.get($mapKey )} instead of $!{mapEntry.get("44")}它与您的几乎相同,但请注意: $userList.keySet()而不是$userList.entrySet()$!{userList.get($mapKey )}而不是$!{mapEntry.get("44")}

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

If you want just to access a specific value of your map try this:如果您只想访问地图的特定值,请尝试以下操作:

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

Per https://velocity.apache.org/engine/1.7/user-guide.html#set :根据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.您可以使用$monkey.Map.get("banana")访问上面的第一个元素以返回字符串 'good',甚至$monkey.Map.banana以返回相同的值。

Per https://velocity.apache.org/engine/1.7/user-guide.html#index-notation根据https://velocity.apache.org/engine/1.7/user-guide.html#index-notation

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM