01: /*
02: * Copyright 2007 Google Inc.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License"); you may not
05: * use this file except in compliance with the License. You may obtain a copy of
06: * the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12: * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13: * License for the specific language governing permissions and limitations under
14: * the License.
15: */
16: package com.google.gwt.json.client;
17:
18: import com.google.gwt.core.client.JavaScriptObject;
19:
20: /**
21: * Represents a JSON string.
22: */
23: public class JSONString extends JSONValue {
24:
25: static JavaScriptObject escapeTable = initEscapeTable();
26:
27: static native String escapeChar(String c) /*-{
28: var lookedUp = @com.google.gwt.json.client.JSONString::escapeTable[c.charCodeAt(0)];
29: return (lookedUp == null) ? c : lookedUp;
30: }-*/;
31:
32: private static native JavaScriptObject initEscapeTable() /*-{
33: var out = [
34: "\\u0000", "\\u0001", "\\u0002", "\\u0003", "\\u0004", "\\u0005",
35: "\\u0006", "\\u0007", "\\b", "\\t", "\\n", "\\u000B",
36: "\\f", "\\r", "\\u000E", "\\u000F", "\\u0010", "\\u0011",
37: "\\u0012", "\\u0013", "\\u0014", "\\u0015", "\\u0016", "\\u0017",
38: "\\u0018", "\\u0019", "\\u001A", "\\u001B", "\\u001C", "\\u001D",
39: "\\u001E", "\\u001F"];
40: out[34] = '\\"';
41: out[92] = '\\\\';
42: return out;
43: }-*/;
44:
45: private String value;
46:
47: /**
48: * Creates a new JSONString from the supplied String.
49: *
50: * @param value a String value
51: * @throws NullPointerException if <code>value</code> is <code>null</code>
52: */
53: public JSONString(String value) {
54: if (value == null) {
55: throw new NullPointerException();
56: }
57: this .value = value;
58: }
59:
60: /**
61: * Returns <code>this</code>, as this is a JSONString.
62: */
63: @Override
64: public JSONString isString() {
65: return this ;
66: }
67:
68: /**
69: * Returns the raw Java string value of this item.
70: */
71: public String stringValue() {
72: return value;
73: }
74:
75: /**
76: * Returns the JSON formatted value of this string, quoted for evaluating in a
77: * JavaScript interpreter.
78: */
79: @Override
80: public String toString() {
81: return escapeValue(value);
82: }
83:
84: private native String escapeValue(String toEscape) /*-{
85: var s = toEscape.replace(/[\x00-\x1F"\\]/g, function(x) {
86: return @com.google.gwt.json.client.JSONString::escapeChar(Ljava/lang/String;)(x);
87: });
88: return "\"" + s + "\"";
89: }-*/;
90: }
|