I have just started using Jackson because of the integration with the Spring Framework and have run into an issue with single quotes in a value. When trying to parse the JSON with jQuery on the page, I get a JavaScript error "SyntaxError: missing ) after argument list"
. I am used to using Gson to serialize my objects and don't run into this issue as Gson will replace the single quote with the Unicode \u0027.
For example;
Java
public final class Person {
private String firstName;
private String lastName;
public Person() {}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastName() {
return lastName;
}
}
JSON
In Jackson
[{"person":{"firstName":"James","lastName":"O'tool"}}]
In Gson
[{"person":{"firstName":"James","lastName":"O\u0027tool"}}]
JavaScript;
// This is where the JavaScript fails with the Jackson serialized object
$.parseJSON('${requestScope.person}');
I have looked for a solution, but am unable to find one. Does anyone know if it is possible to configure Jackson to handle single quotes the same way Gson does?
Thank you for your time.
The other answer shows one way to do this, and it should work pretty well.
But there is another way to do this as well, which is bit less work, explained at "Forcing escaping of HTML characters in JSON using Jackson"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With