0

I have a JSON which has an attribute with its List type. Can someone help me on how to read the value in Apache Velocity template? Following is an example of JSON. The challenge is to read the list of University from JSON and iterate through it.

{
   "StudentName":"XYZ",
  
      "List<Univesity>": [
        {
            "Name": "NYU",
            "City": "NY",
            "Country":"US",
        } ]
}
James Stan
  • 51
  • 6
  • Several questions: under which form is your example data given to Velocity in the context? Is it a String, a Json object instance of some Json library? And do you have access to the Velocity Tools `JsonTool` in your context? – Claude Brisson Nov 26 '22 at 08:01
  • @ClaudeBrisson the input or data source is in JSON. I have provided the sample above and yes I have access to JsonTool. Now to read a non list elements from JSON I did $document.StudentName and store the attribute value in a variable but I can not do the same thing for list for example #set(listofuniversity = $document.List) the special character < & > won;t let me do that. – James Stan Nov 26 '22 at 11:32
  • When you say "the input or data source is in JSON", it doesn't tell us if the JSON is in string format, or if it has already been parsed in a Java Json library, and in this case which Json library you are using... – Claude Brisson Nov 26 '22 at 15:38
  • @ClaudeBrisson we are using the Jackson parser. When the JSON gets to a program which is using velocity for transformation the input JSON is already parsed. – James Stan Nov 26 '22 at 16:38

1 Answers1

1

The solution is dependent upon the JSON library you use, but for many of them, the following code should work:

#set( $universities = $document.get('List<University>') )
#foreach( $university in $universities )
  ... do something ...
#end

The main point to note here is that you can call any Java method on the object you get.

Also, if the security uberspector is not present, for debugging purposes you can display the Java class name of any object in the context, for instance: $document.class.name should display, in your case, something like com.fasterxml.jackson.databind.node.ObjectNode.

Claude Brisson
  • 4,085
  • 1
  • 22
  • 30