I tried using both flexjson.JSONSerializer
and com.fasterxml.jackson.databind.ObjectMapper
in a freemarker template to convert a csv file loaded via the csv data loader csv(menu.csv, {trimCells: true})
to JSON.
When I try to run this, I get the following exception:
...
Caused by: java.lang.UnsupportedOperationException: Operation supported only on TemplateHashModelEx. fmpp.models.CsvSequence does not implement it though.
at freemarker.ext.beans.HashAdapter.getModelEx(HashAdapter.java:186)
at freemarker.ext.beans.HashAdapter.access$000(HashAdapter.java:38)
at freemarker.ext.beans.HashAdapter$1.iterator(HashAdapter.java:99)
at com.fasterxml.jackson.databind.ser.std.MapSerializer.serializeFields(MapSerializer.java:696)
... 46 common frames omitted
I don't know any of the internals of FreeMarker (yet), but this looks to me like the CsvSequence
does implement the freemarker.template.TemplateHashModel
but not freemarker.template.TemplateHashModelEx
.
The only place I found getModelEx
is in the HashAdaptor , so I assume that it uses the newer interface for hashs.
Any idea how to solve this?
The CsvSequence
implements both freemarker.template.TemplateHashModel
and freemarker.template.TemplateSequenceModel
, see http://fmpp.sourceforge.net/api/fmpp/models/CsvSequence.html
CsvSequence is also a hash that contains one key: headers. This is a sequence that stores the header names
As I want to convert only the sequence, not the headers, I can simply convert the CsvSequence
to a normal sequence eg like this:
${JSON.stringify(csvInput[0..])}
or
${JSON.stringify([] + csvInput)}
You can also just convert manually:
<#assign header = _responses["getCSV"]["rawBody"]?keep_before('\r\n')?split(_variables["textquoter"]+_variables["commaseperator"]+_variables["textquoter"])>
<#assign data = _responses["getCSV"]["rawBody"]?keep_after('\r\n')?replace('\r\n',_variables["textquoter"]+_variables["commaseperator"]+_variables["textquoter"])?split(_variables["textquoter"]+_variables["commaseperator"]+_variables["textquoter"])>
<#if data[data?size-1] = ''><#assign data = data[0..data?size-2]></#if>
<#assign json>
<#compress>
[
<#list data as X>
<#assign mod = (X?index) % (header?size)>
<#if mod = 0>{</#if>
"${header[mod]?remove_beginning(_variables["textquoter"])?remove_ending(_variables["textquoter"])}" : "${X?remove_beginning(_variables["textquoter"])?remove_ending(_variables["textquoter"])}"<#if mod lt header?size-1>,</#if>
<#if mod = header?size-1>},</#if>
</#list>
</#compress>
</#assign>
<#assign json = json?remove_ending(',') + '\n]'>
${json}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.