2

I received a message from a queuing service, which I thought would be a UTF-8 encoded String. It turned out to be a quoted and escaped String within a String. That is, the first and last characters of the String itself are ", each newline is two characters \n, quotation marks (numerous because this is XML) are \", and single UTF-8 characters in foreign languages are represented as six characters (e.g., \uABCD). I know I can unwrap all this by rolling my own, but I thought there must be a combination of methods that can do this already. What might that incantation be?

gknauth
  • 2,310
  • 2
  • 29
  • 44
  • possible duplicate of [Howto unescape a Java string literal in Java](http://stackoverflow.com/questions/3537706/howto-unescape-a-java-string-literal-in-java) – njzk2 Dec 05 '14 at 16:16
  • 1
    Is it *actually* just JSON? If so, use a JSON parser. – Jon Skeet Dec 05 '14 at 16:16
  • @JonSkeet It's not JSON. Definitely XML content, escaped. – gknauth Dec 05 '14 at 16:18
  • @JonSkeet: now that you mention it, what gknauth describes does look suspiciously like a json string. – njzk2 Dec 05 '14 at 16:19
  • @gknauth: But escaped as if it's a JSON string? What's producing it? How is it documented? – Jon Skeet Dec 05 '14 at 16:21
  • @JonSkeet It was produced by RabbitMQ, so I think you're on to something, that RabbitMQ used JSON to wrap it. I usually use Jackson to deal with JSON, so I guess I'll give that a try. – gknauth Dec 05 '14 at 16:29

1 Answers1

0

After feedback from @JonSkeet and @njzk2, I came up with this, which worked:

// gradle: 'org.apache.commons:commons-lang3:3.3.2'
import org.apache.commons.lang3.StringEscapeUtils;

String s = serviceThatSometimesReturnsQuotedStringWithinString();
String usable = null;
if (s.length() > 0 && s.charAt(0) == '"' && s.charAt(s.length()-1) == '"') {
  usable = StringEscapeUtils.unescapeEcmaScript(s.substring(1, s.length()-1));
} else {
  usable = s;
}
gknauth
  • 2,310
  • 2
  • 29
  • 44
  • I should also credit this post: http://stackoverflow.com/questions/9359660/json-replace-quotes-and-slashes-but-by-what – gknauth Dec 05 '14 at 17:00