速度模板从数组中删除元素 [英] velocity template drop element from array

查看:40
本文介绍了速度模板从数组中删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在速度模板中删除数组的最后一个元素,然后再将其连接成一个字符串并在className"中显示结果:下面的键:

I'm trying to get the last element of an array in a velocity template dropped before joining it together into a string and showing the result in the "className": key below:

    #set($elem = '"System.NotImplementedException: Test Exception')
    #set($trace = $elem.replace('"',""))
    #set($tracearray = $trace.split("\."))
    #set($arraysize = $tracearray.size())
    #set($lastelem = $tracearray.size() - 1)
    {
      "className":$tracearray.remove($lastelem).toString(),
      "method":"$tracearray[$lastelem]"
    }#if($foreach.hasNext),#end
    #end
  ]

我尝试了几种不同的方法来让数组删除元素并将其连接到一个字符串中,但到目前为止还没有任何运气.

I've tried several different ways to get the array to drop the element and join it together into a string but haven't had any luck so far.

从上面的示例中,我正在寻找要实现的以下输出.

From the above example I'm looking for the following output to be achieved.

{
  "className":"System",
  "method":"NotImplementedException: Test Exception"
}

$elem 变量将保存不同长度的字符串和不同数量的 . 在其中进行拆分,因此数组的长度会有所不同.

The $elem variable will be holding strings of various lengths and with a different number of .'s in them to split on so the lengths of the arrays will vary.

推荐答案

如果只需要删除最后一个元素,何必拆分整个字符串呢?你可以做一些解析来提取类名:

If you only need to remove the last element, why bother splitting the whole string? You could just do some parsing to extract the class name:

#set($elem = '"System.NotImplementedException: Test Exception')                                                                                                                                                 
#set($trace = $elem.replace('"',""))
#set($dot = $trace.lastIndexOf('.'))
#set($className = $trace.substring(0, $dot))
#set($method = $trace.substring($dot + 1))
{
  "className": "$className",
  "method": "$method"
}

或者,为了适应结尾的消息可以包含一个点的事实:

Or, to accomodate the fact that the message at the end could contain a dot:

#set($elem = '"System.NotImplementedException: Test Exception')                                                                                                                                                 
#set($trace = $elem.replace('"',""))
#set($colon = $trace.indexOf(':'))
#set($dot = $trace.lastIndexOf('.', $colon))
#set($className = $trace.substring(0, $dot))
#set($method = $trace.substring($dot + 1))
{
  "className": "$className",
  "method": "$method"
}

使用您选择的方法,您将需要另一个工具来用."连接回数组元素.综上所述,如果您碰巧能够使用自定义工具填充 Velocity 上下文,那么使用此自定义工具可以更轻松地完成所有这些工作.

With the method you have chosen, you would need another tool to join back the array elements with '.'. All this said, if you happen to be able to populate your Velocity context with a custom tool, all this stuff would be more easily done from with this custom tool.

这篇关于速度模板从数组中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆