6

i have a java code like below

  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

#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
daisy
  • 357
  • 3
  • 7
  • 22
  • And the actual output is ? – azro Jul 13 '18 at 06:42
  • 1
    mapEntry is... a map entry. Is there any get() method expecting a key in Map.Entry? Why are you iterating on the map entries if all you need is a specific value? How would you get that specific value in Java code? – JB Nizet Jul 13 '18 at 06:43
  • I don't use Velocity, but why iterate over the `entrySet` when you only want a single value directly from the Map? – Arnold Schrijver Jul 13 '18 at 06:44

2 Answers2

9

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")}

#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")}
pleft
  • 7,567
  • 2
  • 21
  • 45
  • Thanks!. i have one more query if i want to put got value from map to another map in .vm. Its showing extra line of code along with output. Here is my code in .vm #set ($myMap = {}) $myMap.put('Country', $!{userList.get("44")}) $myMap.get('Country') i want only United Kingdom as output. What i am doing wrong – daisy Jul 13 '18 at 07:04
  • Sorry I cannot clearly understand what you are asking, can you also post the actual output? (Although it does not format well in the comments section, it would be better to ask a new question) – pleft Jul 13 '18 at 07:13
0

Per 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.

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

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

Vadzim
  • 24,954
  • 11
  • 143
  • 151