[stringtemplate-interest] Generating JSON using StringTemplate
p_machner at poczta.fm
p_machner at poczta.fm
Tue Nov 15 05:04:56 PST 2011
Hello,
In my application I'm generating Json using StringTemplate. So, for example, I might have a template that looks like so:
{
firstName: '$user.firstName$',
lastName: '$user.lastName$'
}
To this template I can pass the Java user object like so:
User user = //....
template.add("user", user);
Now, this is all nice, but when i.e. the lastname contains an apostrophe (like O'Donovan), my JSON breaks.
What can I do to automatically escape quote signs and apostrophes?
I tried using the following renderer:
stringTemplateGroup.registerRenderer(String.class, new AttributeRenderer() {
@Override
public String toString(Object o, String formatString, Locale locale) {
String result = (String) o;
result = result.replace("\"", "\\\"");
result = result.replace("'", "\'");
return result;
}
});
but this got run on the whole template, not just the parameters that I passed to the template (the User object).
Eventually I got something like this:
{
firstName: \'John\',
lastName: \'O\'Donovan\'
}
which of course is not valid json.
Any ideas on how this escaping can be easily achieved?
Thanks and best regards,
Peter
----------------------------------------------------------------
Najwieksza gielda samochodowa!
http://linkint.pl/f2a7d
More information about the stringtemplate-interest
mailing list