public class JsonUtils extends Object
Modifier and Type | Method and Description |
---|---|
static String |
escapeJsonForEval(String toEscape)
Escapes characters within a JSON string than cannot be passed directly to
eval().
|
static String |
escapeValue(String toEscape)
Returns a quoted, escaped JSON String.
|
static <T extends JavaScriptObject> |
safeEval(String json)
Evaluates a JSON expression safely.
|
static boolean |
safeToEval(String text)
Returns true if the given JSON string may be safely evaluated by
eval() without undesired side effects or security risks. |
static String |
stringify(JavaScriptObject obj)
Converts a value to JSON.
|
static String |
stringify(JavaScriptObject obj,
String space)
Converts a value to JSON.
|
static <T extends JavaScriptObject> |
unsafeEval(String json)
Evaluates a JSON expression using
eval() . |
public static String stringify(JavaScriptObject obj)
public static String stringify(JavaScriptObject obj, String space)
space
- controls the spacing in the final string. Successive levels in the stringification
will each be indented by this string (or the first ten characters of it).public static String escapeJsonForEval(String toEscape)
public static String escapeValue(String toEscape)
public static <T extends JavaScriptObject> T safeEval(String json)
T
- The type of JavaScriptObject that should be returnedjson
- The source JSON textIllegalArgumentException
- if the input is not valid JSONpublic static boolean safeToEval(String text)
eval()
without undesired side effects or security risks. Note that a true
result from this method does not guarantee that the input string is valid
JSON. This method does not consider the contents of quoted strings; it
may still be necessary to perform escaping prior to evaluation for correct
results.
The technique used is taken from RFC 4627.
Note that this function may fail in sufficiently large text in some
browsers (e.g. Chrome). It is always better to use safeEval(java.lang.String)
instead which is safer, faster and also works with large texts but less
lenient than this one for invalid JSON.
public static <T extends JavaScriptObject> T unsafeEval(String json)
eval()
. This method does not
validate the JSON text and should only be used on JSON from trusted
sources. The payload must evaluate to an Object or an Array (not a
primitive or a String).T
- The type of JavaScriptObject that should be returnedjson
- The source JSON textCopyright © 2016. All rights reserved.