I have a task to convert an incoming json message into an xml. I've made a prototype which puts the json message into an org.json.JSONObject. I then cherry pick the fields I'm interested in (not all of them), and plug them into my freemarker template. The output is the desired xml.
Is using freemarker for this sort of thing a bad idea? Objections I've heard are
'it's really for generating html or emails where you fill in the blanks, not for transforming data.''it's difficult to change if the mapping rules (from json to xml) change.''using a pojo based library like model mapper is cleaner.'
However, I like the freemarker approach as it doesn't care whether all the fields (even the ones I'm not interested in) are present/valid on the input json. It only cares about the fields that I have cherry picked. I suppose it follows the 'tolerant reader' pattern that Martin Fowler talks about.
The only concern I would have is the possibility of generating malformed XML. For example if there was text in your JSON message which contained a < character then that character should be escaped as < in the XML text element you generate from that JSON text.
However I'm no Freemarker expert and perhaps there's a feature to encode text so it can be used as an XML text element. I haven't seen that in any tutorials about creating XML using Freemarker, though.
This may not be an issue for you. Or it may not be an issue until you run into, say, a company name containing an ampersand.
Well, for a major bulk conversion, I'd recommend an ETL (Extract, Transform, Load) tool like Talend or Pentaho Kettle (Pentaho DI). They can do just about anything. But they run as stand-alone or embedded applications, so for the occasional conversion using a web service, they're a bit heavy.
Actually, to output XML from a POJO, I've often found it sufficient to simply use a JSP with EL in it. You can use a templating facility like Freemarker - I've used Velocity. You can us Spring MVC. Nothing wrong with any of those.
"privilege" comes from the Latin words for "private" and "law" (legal) and dates to feudal times. To "claim privilege" meant that you were above the laws that applied to the common people.
Paul Clapham wrote:The only concern I would have is the possibility of generating malformed XML...
What I've seen people do when faced with potentially having to escape text which is going to be put into XML is to hard-code CDATA tags in their software which generates XML, so as to make all text elements be CDATA blocks. (You don't need to escape any text in a CDATA block.) Probably that's overkill for you at this point in your development, but it's something that you could easily do later if that issue arises. And you could do it on an element-by-element basis.