使用 apache velocity 读取密钥中带有特殊字符的 JSON

Read JSON with special character in keys using apache velocity

提问人:James Stan 提问时间:11/25/2022 最后编辑:James Stan 更新时间:11/27/2022 访问量:218

问:

我有一个 JSON,它有一个属性,其 List 类型。有人可以帮我如何读取 Apache Velocity 模板中的值吗?以下是 JSON 的示例。挑战在于从 JSON 中读取大学列表并遍历它。

{
   "StudentName":"XYZ",
  
      "List<Univesity>": [
        {
            "Name": "NYU",
            "City": "NY",
            "Country":"US",
        } ]
}
Java Apache 速度

评论

0赞 Claude Brisson 11/26/2022
几个问题:在上下文中,您的示例数据以哪种形式提供给 Velocity?它是 String,还是某个 Json 库的 Json 对象实例?您是否可以在您的环境中访问速度工具?JsonTool
0赞 James Stan 11/26/2022
@ClaudeBrisson输入或数据源是 JSON 格式。我已经提供了上面的示例,是的,我可以访问 JsonTool。现在要从 JSON 中读取非列表元素,我做了$document。StudentName 并将属性值存储在变量中,但我不能对列表做同样的事情,例如 #set(listofuniversity = $document。List<University>)特殊角色<>获胜;让我这样做。
0赞 Claude Brisson 11/26/2022
当您说“输入或数据源是 JSON 格式”时,它不会告诉我们 JSON 是否为字符串格式,或者它是否已经在 Java Json 库中解析过,在这种情况下,您使用的是哪个 JSON 库......
0赞 James Stan 11/27/2022
@ClaudeBrisson我们正在使用 Jackson 解析器。当 JSON 到达使用速度进行转换的程序时,输入 JSON 已被解析。

答:

1赞 Claude Brisson 11/27/2022 #1

该解决方案取决于你使用的 JSON 库,但对于其中许多库,以下代码应该有效:

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

这里要注意的要点是,你可以对你得到的对象调用任何 Java 方法。

此外,如果安全性 uberspector 不存在,出于调试目的,您可以在上下文中显示任何对象的 Java 类名,例如:在您的情况下,应该显示类似 .$document.class.namecom.fasterxml.jackson.databind.node.ObjectNode