Java IRC bot
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

JSONML.java 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. package org.json;
  2. /*
  3. Copyright (c) 2008 JSON.org
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in all
  11. copies or substantial portions of the Software.
  12. The Software shall be used for Good, not Evil.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  19. SOFTWARE.
  20. */
  21. import java.util.Iterator;
  22. /**
  23. * This provides static methods to convert an XML text into a JSONArray or
  24. * JSONObject, and to covert a JSONArray or JSONObject into an XML text using
  25. * the JsonML transform.
  26. * @author JSON.org
  27. * @version 2008-11-20
  28. */
  29. public class JSONML {
  30. /**
  31. * Parse XML values and store them in a JSONArray.
  32. * @param x The XMLTokener containing the source string.
  33. * @param arrayForm true if array form, false if object form.
  34. * @param ja The JSONArray that is containing the current tag or null
  35. * if we are at the outermost level.
  36. * @return A JSONArray if the value is the outermost tag, otherwise null.
  37. * @throws JSONException
  38. */
  39. private static Object parse(XMLTokener x, boolean arrayForm,
  40. JSONArray ja) throws JSONException {
  41. String attribute;
  42. char c;
  43. String closeTag = null;
  44. int i;
  45. JSONArray newja = null;
  46. JSONObject newjo = null;
  47. Object token;
  48. String tagName = null;
  49. // Test for and skip past these forms:
  50. // <!-- ... -->
  51. // <![ ... ]]>
  52. // <! ... >
  53. // <? ... ?>
  54. while (true) {
  55. token = x.nextContent();
  56. if (token == XML.LT) {
  57. token = x.nextToken();
  58. if (token instanceof Character) {
  59. if (token == XML.SLASH) {
  60. // Close tag </
  61. token = x.nextToken();
  62. if (!(token instanceof String)) {
  63. throw new JSONException(
  64. "Expected a closing name instead of '" +
  65. token + "'.");
  66. }
  67. if (x.nextToken() != XML.GT) {
  68. throw x.syntaxError("Misshaped close tag");
  69. }
  70. return token;
  71. } else if (token == XML.BANG) {
  72. // <!
  73. c = x.next();
  74. if (c == '-') {
  75. if (x.next() == '-') {
  76. x.skipPast("-->");
  77. }
  78. x.back();
  79. } else if (c == '[') {
  80. token = x.nextToken();
  81. if (token.equals("CDATA") && x.next() == '[') {
  82. if (ja != null) {
  83. ja.put(x.nextCDATA());
  84. }
  85. } else {
  86. throw x.syntaxError("Expected 'CDATA['");
  87. }
  88. } else {
  89. i = 1;
  90. do {
  91. token = x.nextMeta();
  92. if (token == null) {
  93. throw x.syntaxError("Missing '>' after '<!'.");
  94. } else if (token == XML.LT) {
  95. i += 1;
  96. } else if (token == XML.GT) {
  97. i -= 1;
  98. }
  99. } while (i > 0);
  100. }
  101. } else if (token == XML.QUEST) {
  102. // <?
  103. x.skipPast("?>");
  104. } else {
  105. throw x.syntaxError("Misshaped tag");
  106. }
  107. // Open tag <
  108. } else {
  109. if (!(token instanceof String)) {
  110. throw x.syntaxError("Bad tagName '" + token + "'.");
  111. }
  112. tagName = (String)token;
  113. newja = new JSONArray();
  114. newjo = new JSONObject();
  115. if (arrayForm) {
  116. newja.put(tagName);
  117. if (ja != null) {
  118. ja.put(newja);
  119. }
  120. } else {
  121. newjo.put("tagName", tagName);
  122. if (ja != null) {
  123. ja.put(newjo);
  124. }
  125. }
  126. token = null;
  127. for (;;) {
  128. if (token == null) {
  129. token = x.nextToken();
  130. }
  131. if (token == null) {
  132. throw x.syntaxError("Misshaped tag");
  133. }
  134. if (!(token instanceof String)) {
  135. break;
  136. }
  137. // attribute = value
  138. attribute = (String)token;
  139. if (!arrayForm && (attribute == "tagName" || attribute == "childNode")) {
  140. throw x.syntaxError("Reserved attribute.");
  141. }
  142. token = x.nextToken();
  143. if (token == XML.EQ) {
  144. token = x.nextToken();
  145. if (!(token instanceof String)) {
  146. throw x.syntaxError("Missing value");
  147. }
  148. newjo.accumulate(attribute, JSONObject.stringToValue((String)token));
  149. token = null;
  150. } else {
  151. newjo.accumulate(attribute, "");
  152. }
  153. }
  154. if (arrayForm && newjo.length() > 0) {
  155. newja.put(newjo);
  156. }
  157. // Empty tag <.../>
  158. if (token == XML.SLASH) {
  159. if (x.nextToken() != XML.GT) {
  160. throw x.syntaxError("Misshaped tag");
  161. }
  162. if (ja == null) {
  163. if (arrayForm) {
  164. return newja;
  165. } else {
  166. return newjo;
  167. }
  168. }
  169. // Content, between <...> and </...>
  170. } else {
  171. if (token != XML.GT) {
  172. throw x.syntaxError("Misshaped tag");
  173. }
  174. closeTag = (String)parse(x, arrayForm, newja);
  175. if (closeTag != null) {
  176. if (!closeTag.equals(tagName)) {
  177. throw x.syntaxError("Mismatched '" + tagName +
  178. "' and '" + closeTag + "'");
  179. }
  180. tagName = null;
  181. if (!arrayForm && newja.length() > 0) {
  182. newjo.put("childNodes", newja);
  183. }
  184. if (ja == null) {
  185. if (arrayForm) {
  186. return newja;
  187. } else {
  188. return newjo;
  189. }
  190. }
  191. }
  192. }
  193. }
  194. } else {
  195. if (ja != null) {
  196. ja.put(token instanceof String ?
  197. JSONObject.stringToValue((String)token) : token);
  198. }
  199. }
  200. }
  201. }
  202. /**
  203. * Convert a well-formed (but not necessarily valid) XML string into a
  204. * JSONArray using the JsonML transform. Each XML tag is represented as
  205. * a JSONArray in which the first element is the tag name. If the tag has
  206. * attributes, then the second element will be JSONObject containing the
  207. * name/value pairs. If the tag contains children, then strings and
  208. * JSONArrays will represent the child tags.
  209. * Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored.
  210. * @param string The source string.
  211. * @return A JSONArray containing the structured data from the XML string.
  212. * @throws JSONException
  213. */
  214. public static JSONArray toJSONArray(String string) throws JSONException {
  215. return toJSONArray(new XMLTokener(string));
  216. }
  217. /**
  218. * Convert a well-formed (but not necessarily valid) XML string into a
  219. * JSONArray using the JsonML transform. Each XML tag is represented as
  220. * a JSONArray in which the first element is the tag name. If the tag has
  221. * attributes, then the second element will be JSONObject containing the
  222. * name/value pairs. If the tag contains children, then strings and
  223. * JSONArrays will represent the child content and tags.
  224. * Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored.
  225. * @param x An XMLTokener.
  226. * @return A JSONArray containing the structured data from the XML string.
  227. * @throws JSONException
  228. */
  229. public static JSONArray toJSONArray(XMLTokener x) throws JSONException {
  230. return (JSONArray)parse(x, true, null);
  231. }
  232. /**
  233. * Convert a well-formed (but not necessarily valid) XML string into a
  234. * JSONObject using the JsonML transform. Each XML tag is represented as
  235. * a JSONObject with a "tagName" property. If the tag has attributes, then
  236. * the attributes will be in the JSONObject as properties. If the tag
  237. * contains children, the object will have a "childNodes" property which
  238. * will be an array of strings and JsonML JSONObjects.
  239. * Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored.
  240. * @param x An XMLTokener of the XML source text.
  241. * @return A JSONObject containing the structured data from the XML string.
  242. * @throws JSONException
  243. */
  244. public static JSONObject toJSONObject(XMLTokener x) throws JSONException {
  245. return (JSONObject)parse(x, false, null);
  246. }
  247. /**
  248. * Convert a well-formed (but not necessarily valid) XML string into a
  249. * JSONObject using the JsonML transform. Each XML tag is represented as
  250. * a JSONObject with a "tagName" property. If the tag has attributes, then
  251. * the attributes will be in the JSONObject as properties. If the tag
  252. * contains children, the object will have a "childNodes" property which
  253. * will be an array of strings and JsonML JSONObjects.
  254. * Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored.
  255. * @param string The XML source text.
  256. * @return A JSONObject containing the structured data from the XML string.
  257. * @throws JSONException
  258. */
  259. public static JSONObject toJSONObject(String string) throws JSONException {
  260. return toJSONObject(new XMLTokener(string));
  261. }
  262. /**
  263. * Reverse the JSONML transformation, making an XML text from a JSONArray.
  264. * @param ja A JSONArray.
  265. * @return An XML string.
  266. * @throws JSONException
  267. */
  268. public static String toString(JSONArray ja) throws JSONException {
  269. Object e;
  270. int i;
  271. JSONObject jo;
  272. String k;
  273. Iterator keys;
  274. int length;
  275. StringBuffer sb = new StringBuffer();
  276. String tagName;
  277. String v;
  278. // Emit <tagName
  279. tagName = ja.getString(0);
  280. XML.noSpace(tagName);
  281. tagName = XML.escape(tagName);
  282. sb.append('<');
  283. sb.append(tagName);
  284. e = ja.opt(1);
  285. if (e instanceof JSONObject) {
  286. i = 2;
  287. jo = (JSONObject)e;
  288. // Emit the attributes
  289. keys = jo.keys();
  290. while (keys.hasNext()) {
  291. k = keys.next().toString();
  292. XML.noSpace(k);
  293. v = jo.optString(k);
  294. if (v != null) {
  295. sb.append(' ');
  296. sb.append(XML.escape(k));
  297. sb.append('=');
  298. sb.append('"');
  299. sb.append(XML.escape(v));
  300. sb.append('"');
  301. }
  302. }
  303. } else {
  304. i = 1;
  305. }
  306. //Emit content in body
  307. length = ja.length();
  308. if (i >= length) {
  309. sb.append('/');
  310. sb.append('>');
  311. } else {
  312. sb.append('>');
  313. do {
  314. e = ja.get(i);
  315. i += 1;
  316. if (e != null) {
  317. if (e instanceof String) {
  318. sb.append(XML.escape(e.toString()));
  319. } else if (e instanceof JSONObject) {
  320. sb.append(toString((JSONObject)e));
  321. } else if (e instanceof JSONArray) {
  322. sb.append(toString((JSONArray)e));
  323. }
  324. }
  325. } while (i < length);
  326. sb.append('<');
  327. sb.append('/');
  328. sb.append(tagName);
  329. sb.append('>');
  330. }
  331. return sb.toString();
  332. }
  333. /**
  334. * Reverse the JSONML transformation, making an XML text from a JSONObject.
  335. * The JSONObject must contain a "tagName" property. If it has children,
  336. * then it must have a "childNodes" property containing an array of objects.
  337. * The other properties are attributes with string values.
  338. * @param jo A JSONObject.
  339. * @return An XML string.
  340. * @throws JSONException
  341. */
  342. public static String toString(JSONObject jo) throws JSONException {
  343. StringBuffer sb = new StringBuffer();
  344. Object e;
  345. int i;
  346. JSONArray ja;
  347. String k;
  348. Iterator keys;
  349. int len;
  350. String tagName;
  351. String v;
  352. //Emit <tagName
  353. tagName = jo.optString("tagName");
  354. if (tagName == null) {
  355. return XML.escape(jo.toString());
  356. }
  357. XML.noSpace(tagName);
  358. tagName = XML.escape(tagName);
  359. sb.append('<');
  360. sb.append(tagName);
  361. //Emit the attributes
  362. keys = jo.keys();
  363. while (keys.hasNext()) {
  364. k = keys.next().toString();
  365. if (!k.equals("tagName") && !k.equals("childNodes")) {
  366. XML.noSpace(k);
  367. v = jo.optString(k);
  368. if (v != null) {
  369. sb.append(' ');
  370. sb.append(XML.escape(k));
  371. sb.append('=');
  372. sb.append('"');
  373. sb.append(XML.escape(v));
  374. sb.append('"');
  375. }
  376. }
  377. }
  378. //Emit content in body
  379. ja = jo.optJSONArray("childNodes");
  380. if (ja == null) {
  381. sb.append('/');
  382. sb.append('>');
  383. } else {
  384. sb.append('>');
  385. len = ja.length();
  386. for (i = 0; i < len; i += 1) {
  387. e = ja.get(i);
  388. if (e != null) {
  389. if (e instanceof String) {
  390. sb.append(XML.escape(e.toString()));
  391. } else if (e instanceof JSONObject) {
  392. sb.append(toString((JSONObject)e));
  393. } else if (e instanceof JSONArray) {
  394. sb.append(toString((JSONArray)e));
  395. }
  396. }
  397. }
  398. sb.append('<');
  399. sb.append('/');
  400. sb.append(tagName);
  401. sb.append('>');
  402. }
  403. return sb.toString();
  404. }
  405. }