Re: Return Map from Directive?
Mike Kienenberger <[email protected]> Mon, 3 Feb 2020 14:00:26 -0500
| Newsgroups | gmane.comp.jakarta.velocity.user |
|---|---|
| Message-ID | <CAM1yOjZH7Rk7TjyW7n=ehLhCiyGzDkyS7kqT_rBH_T6DiwH3Jw@mail.gmail.com> |
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 <[email protected]> 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