velocity template drop element from array

女生的网名这么多〃 提交于 2021-02-10 14:14:39

问题


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

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.


回答1:


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

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.



来源:https://stackoverflow.com/questions/42378967/velocity-template-drop-element-from-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!