1 package org
.gaixie
.jibu
.json
;
3 Copyright (c) 2002 JSON.org
5 Permission is hereby granted, free of charge, to any person obtaining a copy
6 of this software and associated documentation files (the "Software"), to deal
7 in the Software without restriction, including without limitation the rights
8 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 copies of the Software, and to permit persons to whom the Software is
10 furnished to do so, subject to the following conditions:
12 The above copyright notice and this permission notice shall be included in all
13 copies or substantial portions of the Software.
15 The Software shall be used for Good, not Evil.
17 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26 import java
.util
.Iterator
;
30 * This provides static methods to convert an XML text into a JSONObject,
31 * and to covert a JSONObject into an XML text.
37 /** The Character '&'. */
38 public static final Character AMP
= new Character('&');
40 /** The Character '''. */
41 public static final Character APOS
= new Character('\'');
43 /** The Character '!'. */
44 public static final Character BANG
= new Character('!');
46 /** The Character '='. */
47 public static final Character EQ
= new Character('=');
49 /** The Character '>'. */
50 public static final Character GT
= new Character('>');
52 /** The Character '<'. */
53 public static final Character LT
= new Character('<');
55 /** The Character '?'. */
56 public static final Character QUEST
= new Character('?');
58 /** The Character '"'. */
59 public static final Character QUOT
= new Character('"');
61 /** The Character '/'. */
62 public static final Character SLASH
= new Character('/');
65 * Replace special characters with XML escapes:
67 * & <small>(ampersand)</small> is replaced by &amp;
68 * < <small>(less than)</small> is replaced by &lt;
69 * > <small>(greater than)</small> is replaced by &gt;
70 * " <small>(double quote)</small> is replaced by &quot;
72 * @param string The string to be escaped.
73 * @return The escaped string.
75 public static String
escape(String string
) {
76 StringBuffer sb
= new StringBuffer();
77 for (int i
= 0, len
= string
.length(); i
< len
; i
++) {
78 char c
= string
.charAt(i
);
100 * Throw an exception if the string contains whitespace.
101 * Whitespace is not allowed in tagNames and attributes.
103 * @throws JSONException
105 public static void noSpace(String string
) throws JSONException
{
106 int i
, length
= string
.length();
108 throw new JSONException("Empty string.");
110 for (i
= 0; i
< length
; i
+= 1) {
111 if (Character
.isWhitespace(string
.charAt(i
))) {
112 throw new JSONException("'" + string
+
113 "' contains a space character.");
119 * Scan the content following the named tag, attaching it to the context.
120 * @param x The XMLTokener containing the source string.
121 * @param context The JSONObject that will include the new material.
122 * @param name The tag name.
123 * @return true if the close tag is processed.
124 * @throws JSONException
126 private static boolean parse(XMLTokener x
, JSONObject context
,
127 String name
) throws JSONException
{
135 // Test for and skip past these forms:
140 // Report errors for these forms:
152 if (x
.next() == '-') {
157 } else if (c
== '[') {
159 if (t
.equals("CDATA")) {
160 if (x
.next() == '[') {
162 if (s
.length() > 0) {
163 context
.accumulate("content", s
);
168 throw x
.syntaxError("Expected 'CDATA['");
174 throw x
.syntaxError("Missing '>' after '<!'.");
175 } else if (t
== LT
) {
177 } else if (t
== GT
) {
182 } else if (t
== QUEST
) {
188 } else if (t
== SLASH
) {
194 throw x
.syntaxError("Mismatched close tag" + t
);
196 if (!t
.equals(name
)) {
197 throw x
.syntaxError("Mismatched " + name
+ " and " + t
);
199 if (x
.nextToken() != GT
) {
200 throw x
.syntaxError("Misshaped close tag");
204 } else if (t
instanceof Character
) {
205 throw x
.syntaxError("Misshaped tag");
212 o
= new JSONObject();
220 if (t
instanceof String
) {
225 if (!(t
instanceof String
)) {
226 throw x
.syntaxError("Missing value");
228 o
.accumulate(s
, JSONObject
.stringToValue((String
)t
));
236 } else if (t
== SLASH
) {
237 if (x
.nextToken() != GT
) {
238 throw x
.syntaxError("Misshaped tag");
240 context
.accumulate(n
, o
);
243 // Content, between <...> and </...>
245 } else if (t
== GT
) {
250 throw x
.syntaxError("Unclosed tag " + n
);
253 } else if (t
instanceof String
) {
255 if (s
.length() > 0) {
256 o
.accumulate("content", JSONObject
.stringToValue(s
));
261 } else if (t
== LT
) {
262 if (parse(x
, o
, n
)) {
263 if (o
.length() == 0) {
264 context
.accumulate(n
, "");
265 } else if (o
.length() == 1 &&
266 o
.opt("content") != null) {
267 context
.accumulate(n
, o
.opt("content"));
269 context
.accumulate(n
, o
);
276 throw x
.syntaxError("Misshaped tag");
284 * Convert a well-formed (but not necessarily valid) XML string into a
285 * JSONObject. Some information may be lost in this transformation
286 * because JSON is a data format and XML is a document format. XML uses
287 * elements, attributes, and content text, while JSON uses unordered
288 * collections of name/value pairs and arrays of values. JSON does not
289 * does not like to distinguish between elements and attributes.
290 * Sequences of similar elements are represented as JSONArrays. Content
291 * text may be placed in a "content" member. Comments, prologs, DTDs, and
292 * <code><[ [ ]]></code> are ignored.
293 * @param string The source string.
294 * @return A JSONObject containing the structured data from the XML string.
295 * @throws JSONException
297 public static JSONObject
toJSONObject(String string
) throws JSONException
{
298 JSONObject o
= new JSONObject();
299 XMLTokener x
= new XMLTokener(string
);
300 while (x
.more() && x
.skipPast("<")) {
308 * Convert a JSONObject into a well-formed, element-normal XML string.
309 * @param o A JSONObject.
311 * @throws JSONException
313 public static String
toString(Object o
) throws JSONException
{
314 return toString(o
, null);
319 * Convert a JSONObject into a well-formed, element-normal XML string.
320 * @param o A JSONObject.
321 * @param tagName The optional name of the enclosing tag.
323 * @throws JSONException
325 public static String
toString(Object o
, String tagName
)
326 throws JSONException
{
327 StringBuffer b
= new StringBuffer();
336 if (o
instanceof JSONObject
) {
340 if (tagName
!= null) {
346 // Loop thru the keys.
350 while (keys
.hasNext()) {
351 k
= keys
.next().toString();
356 if (v
instanceof String
) {
362 // Emit content in body
364 if (k
.equals("content")) {
365 if (v
instanceof JSONArray
) {
368 for (i
= 0; i
< len
; i
+= 1) {
372 b
.append(escape(ja
.get(i
).toString()));
375 b
.append(escape(v
.toString()));
378 // Emit an array of similar keys
380 } else if (v
instanceof JSONArray
) {
383 for (i
= 0; i
< len
; i
+= 1) {
385 if (v
instanceof JSONArray
) {
389 b
.append(toString(v
));
394 b
.append(toString(v
, k
));
397 } else if (v
.equals("")) {
402 // Emit a new tag <k>
405 b
.append(toString(v
, k
));
408 if (tagName
!= null) {
410 // Emit the </tagname> close tag
418 // XML does not have good support for arrays. If an array appears in a place
419 // where XML is lacking, synthesize an <array> element.
421 } else if (o
instanceof JSONArray
) {
424 for (i
= 0; i
< len
; ++i
) {
426 b
.append(toString(v
, (tagName
== null) ?
"array" : tagName
));
430 s
= (o
== null) ?
"null" : escape(o
.toString());
431 return (tagName
== null) ?
"\"" + s
+ "\"" :
432 (s
.length() == 0) ?
"<" + tagName
+ "/>" :
433 "<" + tagName
+ ">" + s
+ "</" + tagName
+ ">";