Search code examples
gsonspecial-characters

Gson library when parse string contain special char \u


I have a simple code like that:

 JsonParser parser = new JsonParser();
 JsonElement element = parser.parse("{\"description\":\"c:\\userDescription.txt\"}");
 JsonObject attributes = element.getAsJsonObject();
 System.out.println(attributes);

I expect the outout is:

{"description":"c:\userDescription.txt"}

but actually I have the exeption:

Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.NumberFormatException: For input string: "serD"

Can you help me, what should the input is to get the expect output:

 {"description":"c:\userDescription.txt"}

Solution

  • The following Java string is one character long, the \ character:

    String s = "\\";
    

    Like Java, JSON uses \ as its escape character. So you need to escape for Java and for JSON. Try this:

    JsonElement element = parser.parse("{\"description\":\"c:\\\\userDescription.txt\"}");