JSONUtil { public static String unescape(String input) { StringBuilder builder = new StringBuilder(); int i = 0; while (i < input.length()) { char delimiter = input.charAt(i); i++; if(delimiter == '\\' && i < input.length()) { char ch = input.charAt(i); i++; if(ch == '\\' || ch == '/' || ch == '"' || ch == '\'') { builder.append(ch); } else if(ch == 'n') builder.append('\n'); else if(ch == 'r') builder.append('\r'); else if(ch == 't') builder.append('\t'); else if(ch == 'b') builder.append('\b'); else if(ch == 'f') builder.append('\f'); else if(ch == 'u') { StringBuilder hex = new StringBuilder(); if (i+4 > input.length()) { throw new RuntimeException("Not enough unicode digits! "); } for (char x : input.substring(i, i + 4).toCharArray()) { if(!Character.isLetterOrDigit(x)) { throw new RuntimeException("Bad character in unicode escape."); } hex.append(Character.toLowerCase(x)); } i+=4; int code = Integer.parseInt(hex.toString(), 16); builder.append((char) code); } else { throw new RuntimeException("Illegal escape sequence: \\"+ch); } } else { builder.append(delimiter); } } return builder.toString(); }  static Object parseString(String value); static void writeXML(Parameters p, XMLStreamWriter xml); static String escape(String input); static String unescape(String input); static final XMLOutputFactory xmlOutputFactory; }
@Test public void testUnescape() throws Exception { String testShort = "Eating a piece of \u03c0 (pi)"; assertEquals("Eating a piece of \\u03c0 (pi)", escape(testShort)); String testLong = "I stole this guy from wikipedia: \ud83d\ude02"; assertEquals("I stole this guy from wikipedia: \\ud83d\\ude02", escape(testLong)); String testQuote = "here it comes \" to wreck the day..."; assertEquals("here it comes \\\" to wreck the day...", escape(testQuote)); String testNewline = "here it comes \n to wreck the day..."; assertEquals("here it comes \\n to wreck the day...", escape(testNewline)); String testBackslash = "here it comes \\ to wreck the day..."; assertEquals("here it comes \\\\ to wreck the day...", escape(testBackslash)); String testAsciiEscapes = "\\\r\n\t\b\f \\hmm\\ \f\b\n\r\\"; assertEquals(testAsciiEscapes, unescape(escape(testAsciiEscapes))); assertEquals(testLong, unescape(escape(testLong))); assertEquals(testShort, unescape(escape(testShort))); }