What's the right way to escape a string before writing it to an Apache Commons PropertiesConfiguration?
We have a ".properties" file that has some values persisted as JSON. I keep getting bitten by special characters, though -- the org.json.JSONObject isn't very verbose about what causes it to choke, so it takes forever to figure out that I wrote {"key":"this is a \"Value\""}
, but I read {"key":"this is a "Value""}
. Obviously, the latter is going to give the JSON parser fits. Rather than poking at it by trial-and-error, can anybody just tell me the right way to escape the value (which in this case is of course the entire JSON string..开发者_Python百科.) before passing it to the PropertiesConfiguration class to be written to a file?
Backslash is ignored in property files. You need to use Unicode encoding like this,
"this is a \u005c"Value\u005c""
I think I may have found the disconnect. I thought we had something along the lines of
PropertiesConfiguration pc = new PropertiesConfiguration();
pc.addProperty("SomeKey",
new JSONObject().put("Stuff", getUserInput()).toString());
pc.save(myWriter);
Now, imagine that the user supplies the string This is "Interesting"...
. My problem comes because while the string will be stored with the quotes properly escaped, the properties file will wind up with
SomeKey={\"SomeKey\":\"This is \"Interesting\"\"}
which is of course horribly broken. Here's why it was happening (I think). Instead of using the PropertiesConfiguration class to create the properties file as in the ideal code above, the original code was more like
myWriter.write(keyName + "=" +
new JSONObject().put("Stuff", getUserInput()).toString());
which of course only escapes the user input for the JSON, but does not further escape the JSON for the Properties parser. I can't swear to it without additional testing, but it looks like the pc.AddProperty()
method will escape its arguments (again) if need be.
End result: it's my fault that I assumed the guy who wrote the code I'm working on was using the APIs provided to him, rather than "going rogue" and trying to create the required format directly.
精彩评论