This question is unique and differs from this one as it specifically addresses the representation of JSON strings serialized from Java in literal form in JavaScript, with a focus beyond just double quotes.
In my scenario, I am serializing a JSON object in Java using Gson, but encountering difficulties when attempting to parse it in Javascript using JSON.parse. The issue arises when dealing with escaped double quotes in the Java object, which is surprising as Gson should handle proper escaping. Since JSON serialization is language-agnostic, transitioning from Java serialization to JavaScript deserialization should be straightforward.
Below is a snippet of the minimal code:
Java serialization
import java.util.*;
import java.lang.reflect.Type;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
class LOV {
List<String> values;
public LOV(List<String> values) {
this.values = values;
}
}
public class FooMain {
private static final Gson gson = new GsonBuilder().serializeNulls().create();
@SuppressWarnings("unchecked")
public static <T> T fromJson(String json, Class<T> classOfT) {
T target = (T) gson.fromJson(json, (Type) classOfT);
return target;
}
public static void main(String args[]) {
List<String> values = new ArrayList<>();
values.add("\"foo\"");
LOV lov = new LOV(values);
String s = gson.toJson(lov);
System.out.printf("Stringified JSON is: [%s]\n", s);
LOV lov2 = fromJson(s, LOV.class);
}
}
The above code demonstrates successful serialization and deserialization. Additionally, an equals
method was implemented for the LOV class to confirm that the re-internalized object (lov2
) matches the original serialized object.
The console output from the code is:
Stringified JSON is: [{"values":["\"foo\""]}]
JavaScript internalization
However, attempting to parse the Java-created string in JavaScript results in an error:
Uncaught SyntaxError: Unexpected token f in JSON at position 13(…)
Solution
To address this issue, I followed the accepted answer and suggestions provided in the comments. Several characters needed to be escaped on the Java side, including:
s.replace("\\", "\\\\")
s.replace("\"", "\\\"")
s.replace("'", "\\'")
On the JavaScript side, additional escaping was necessary:
JSON.parse('the string literal prepared by Java'.replace(/\t/g, "\\t"));
While this approach worked, it became complex and ensuring all cases were covered was challenging. Ultimately, I opted for using StringEscapeUtils.escapeEcmaScript, which simplified the process. By applying escapeEcmaScript
to the string, a straightforward
JSON.parse('the string literal prepared by Java')
sufficed for JavaScript parsing.