【问题标题】:get particular value by key from Hashmap in velocity template从速度模板中的 Hashmap 中按键获取特定值
【发布时间】:2020-02-18 20:48:32
【问题描述】:

我有一个类似下面的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

【问题讨论】:

  • 而实际输出是?
  • mapEntry 是...一个地图条目。是否有任何 get() 方法需要 Map.Entry 中的键?如果您只需要一个特定的值,为什么还要迭代地图条目?您将如何在 Java 代码中获得该特定值?
  • 我不使用 Velocity,但是当您只需要直接来自 Map 的单个值时,为什么要遍历 entrySet

标签: java velocity velocity-template-language


【解决方案1】:

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

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

如果您只想访问地图的特定值,请尝试以下操作:

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

【讨论】:

  • 谢谢!。如果我想将得到的值从映射到.vm 中的另一个映射,我还有一个查询。它显示了额外的代码行以及输出。这是我在 .vm #set ($myMap = {}) $myMap.put('Country', $!{userList.get("44")}) $myMap.get('Country') 中的代码我只想要英国作为输出。我做错了什么
  • 对不起,我不能清楚地理解你在问什么,你也可以发布实际的输出吗? (虽然在cmets部分格式不太好,但还是问个新问题比较好)
【解决方案2】:

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

你可以使用上面的第一个元素 $monkey.Map.get("banana") 返回一个字符串“好”,甚至 $monkey.Map.banana 返回相同的值。

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

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

【讨论】:

    猜你喜欢
    • 2014-12-03
    • 2012-12-30
    • 1970-01-01
    • 1970-01-01
    • 2012-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-10
    相关资源
    最近更新 更多