javavelocityapache-velocity

Read JSON with special character in keys using apache velocity


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",
        } ]
}

Solution

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