-2

Does anyone know of a library function to escape and surround a string value of an object with quotes unless it is null?

For example, the function should process:

  • "hello" as "\"hello\""
  • null as "null"
  • Long.valueOf(2L) as "\"2\""
  • "" as "\"\""
  • "I\'m \"quoted\"" as "\"I\\\'m \\\"quoted\\\""

Clearly this is trivial to implement in Java, but I'm looking for a function in an existing library (e.g. JDK, Commons Lang, Spring ...) I'd be surprised if this hasn't been done before.

For reference, this is for converting objects to JavaScript strings.

4

3 回答 3

2

Forget the Quoting, really. If you want to write Java to JS, use Jackson:

import java.util.Date;

import org.codehaus.jackson.map.ObjectMapper;

public class Teste {

    /**
     * @param args
     */
    public static void main(String[] args) throws Exception {
        printAsJs(null);
        printAsJs(5L);
        printAsJs("Hello!");
        printAsJs(new Date());
    }

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    public static void printAsJs(Object o) throws Exception {
        System.out.println(OBJECT_MAPPER.writeValueAsString(o));
    }

}

If you need extra handlers to format as JS, extend ObjectMapper with your desired needs

Thank you come again

于 2013-01-15T17:47:56.867 回答
0

You can write your own using StringUtils.

import static org.apache.commongs.lang.StringUtils.*;
import org.apache.commons.lang.StringEscapeUtils.*;

public void quote(String x) {
  return escapeJavaScript(defaultString(x, "null").replaceFirst("^(.*)$", "\"$1\"")));
}
于 2013-01-15T16:46:02.590 回答
0

Your requirements are

  • Surround output with quotes
  • Escape quotes
  • Handle null different (no surrounding quotes)

I don't know any library method fulfilling your requirements.

Anyway, it can be implemented with a one line method:

public static String quoteAndEscape(Object o) {
    return o == null ? "null" : "\"" + StringEscapeUtils.escapeJava(String.valueOf(o)) + "\"";
}
于 2013-01-15T17:09:47.997 回答