What you typically do is insert a "tool" (which is a POJO -- any java
class instance) into your context, then call a method on that tool to
do something.

How you insert the tool depends how you use Velocity (do you set it up
programmatically in java? using velocity tools?  using ant? etc).

After the tool is in the context, you would do something like this:

#set ($mapping = $jsonTool.convertJSONStringToJavaMap($userid) )

This assumes that the object you inserted as "jasonTool" has a method
signature like this:

public Map convertJSONStringToJavaMap(UserIdType userid)

Note that there is nothing special about an object inserted as a tool
or about the methods on the tool.

The documentation here is probably a good place to start learning
about tools, although you do not have to use this approach to insert a
tool:

https://velocity.apache.org/tools/devel/

Also, it does look like VelocityTools already has a JSON tool object
-- Maybe it already does what you want without any effort on your
part.

But you can also insert tools as simply as

context.put("jsonTool", new JsonTool());



On Mon, Feb 3, 2020 at 2:31 AM Net Wolf <netwol...@gmail.com> wrote:
>
> Hi.
>
> I'm hoping to extend Velocity to be able to convert a JSON string to a Java 
> Map so that template authors can map values in Velocity.
>
> Something like:
> # set mappings = JsonToMap ($jsonString)
> # set username = $mappings($userid)
>
> I thought I could just write a directive for JsonToMap but directives seem to 
> return a string rather than a map.
>
> Alternatively could I add a method in the context somehow? Perhaps I could 
> then call something like...
>
> # set username = $jsonString.toMap().get($userid)
>
> Sorry if I've misunderstood something fundamental in velocity. I'm interested 
> in receiving some guidance on the best way to do this sort of conversion.
>
> Thanks in advance.
> Net Wolf

---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscr...@velocity.apache.org
For additional commands, e-mail: user-h...@velocity.apache.org

Reply via email to