1
0
Fork 0
mirror of https://github.com/ethauvin/JSON-java.git synced 2025-06-17 07:50:52 -07:00
This commit is contained in:
Douglas Crockford 2011-10-04 21:03:39 -07:00
parent e13de0b221
commit 294c16be1b

View file

@ -28,14 +28,14 @@ import java.util.Iterator;
/** /**
* This provides static methods to convert an XML text into a JSONArray or * This provides static methods to convert an XML text into a JSONArray or
* JSONObject, and to covert a JSONArray or JSONObject into an XML text using * JSONObject, and to covert a JSONArray or JSONObject into an XML text using
* the JsonML transform. * the JsonML transform.
* @author JSON.org * @author JSON.org
* @version 2011-10-03 * @version 2011-10-04
*/ */
public class JSONML { public class JSONML {
/** /**
* Parse XML values and store them in a JSONArray. * Parse XML values and store them in a JSONArray.
* @param x The XMLTokener containing the source string. * @param x The XMLTokener containing the source string.
@ -46,185 +46,185 @@ public class JSONML {
* @throws JSONException * @throws JSONException
*/ */
private static Object parse( private static Object parse(
XMLTokener x, XMLTokener x,
boolean arrayForm, boolean arrayForm,
JSONArray ja JSONArray ja
) throws JSONException { ) throws JSONException {
String attribute; String attribute;
char c; char c;
String closeTag = null; String closeTag = null;
int i; int i;
JSONArray newja = null; JSONArray newja = null;
JSONObject newjo = null; JSONObject newjo = null;
Object token; Object token;
String tagName = null; String tagName = null;
// Test for and skip past these forms: // Test for and skip past these forms:
// <!-- ... --> // <!-- ... -->
// <![ ... ]]> // <![ ... ]]>
// <! ... > // <! ... >
// <? ... ?> // <? ... ?>
while (true) { while (true) {
token = x.nextContent(); token = x.nextContent();
if (token == XML.LT) { if (token == XML.LT) {
token = x.nextToken(); token = x.nextToken();
if (token instanceof Character) { if (token instanceof Character) {
if (token == XML.SLASH) { if (token == XML.SLASH) {
// Close tag </ // Close tag </
token = x.nextToken(); token = x.nextToken();
if (!(token instanceof String)) { if (!(token instanceof String)) {
throw new JSONException( throw new JSONException(
"Expected a closing name instead of '" + "Expected a closing name instead of '" +
token + "'."); token + "'.");
} }
if (x.nextToken() != XML.GT) { if (x.nextToken() != XML.GT) {
throw x.syntaxError("Misshaped close tag"); throw x.syntaxError("Misshaped close tag");
} }
return token; return token;
} else if (token == XML.BANG) { } else if (token == XML.BANG) {
// <! // <!
c = x.next(); c = x.next();
if (c == '-') { if (c == '-') {
if (x.next() == '-') { if (x.next() == '-') {
x.skipPast("-->"); x.skipPast("-->");
} }
x.back(); x.back();
} else if (c == '[') { } else if (c == '[') {
token = x.nextToken(); token = x.nextToken();
if (token.equals("CDATA") && x.next() == '[') { if (token.equals("CDATA") && x.next() == '[') {
if (ja != null) { if (ja != null) {
ja.put(x.nextCDATA()); ja.put(x.nextCDATA());
} }
} else { } else {
throw x.syntaxError("Expected 'CDATA['"); throw x.syntaxError("Expected 'CDATA['");
} }
} else { } else {
i = 1; i = 1;
do { do {
token = x.nextMeta(); token = x.nextMeta();
if (token == null) { if (token == null) {
throw x.syntaxError("Missing '>' after '<!'."); throw x.syntaxError("Missing '>' after '<!'.");
} else if (token == XML.LT) { } else if (token == XML.LT) {
i += 1; i += 1;
} else if (token == XML.GT) { } else if (token == XML.GT) {
i -= 1; i -= 1;
} }
} while (i > 0); } while (i > 0);
} }
} else if (token == XML.QUEST) { } else if (token == XML.QUEST) {
// <? // <?
x.skipPast("?>"); x.skipPast("?>");
} else { } else {
throw x.syntaxError("Misshaped tag"); throw x.syntaxError("Misshaped tag");
} }
// Open tag < // Open tag <
} else { } else {
if (!(token instanceof String)) { if (!(token instanceof String)) {
throw x.syntaxError("Bad tagName '" + token + "'."); throw x.syntaxError("Bad tagName '" + token + "'.");
} }
tagName = (String)token; tagName = (String)token;
newja = new JSONArray(); newja = new JSONArray();
newjo = new JSONObject(); newjo = new JSONObject();
if (arrayForm) { if (arrayForm) {
newja.put(tagName); newja.put(tagName);
if (ja != null) { if (ja != null) {
ja.put(newja); ja.put(newja);
} }
} else { } else {
newjo.put("tagName", tagName); newjo.put("tagName", tagName);
if (ja != null) { if (ja != null) {
ja.put(newjo); ja.put(newjo);
} }
} }
token = null; token = null;
for (;;) { for (;;) {
if (token == null) { if (token == null) {
token = x.nextToken(); token = x.nextToken();
} }
if (token == null) { if (token == null) {
throw x.syntaxError("Misshaped tag"); throw x.syntaxError("Misshaped tag");
} }
if (!(token instanceof String)) { if (!(token instanceof String)) {
break; break;
} }
// attribute = value // attribute = value
attribute = (String)token; attribute = (String)token;
if (!arrayForm && (attribute == "tagName" || attribute == "childNode")) { if (!arrayForm && (attribute == "tagName" || attribute == "childNode")) {
throw x.syntaxError("Reserved attribute."); throw x.syntaxError("Reserved attribute.");
} }
token = x.nextToken(); token = x.nextToken();
if (token == XML.EQ) { if (token == XML.EQ) {
token = x.nextToken(); token = x.nextToken();
if (!(token instanceof String)) { if (!(token instanceof String)) {
throw x.syntaxError("Missing value"); throw x.syntaxError("Missing value");
} }
newjo.accumulate(attribute, XML.stringToValue((String)token)); newjo.accumulate(attribute, XML.stringToValue((String)token));
token = null; token = null;
} else { } else {
newjo.accumulate(attribute, ""); newjo.accumulate(attribute, "");
} }
} }
if (arrayForm && newjo.length() > 0) { if (arrayForm && newjo.length() > 0) {
newja.put(newjo); newja.put(newjo);
} }
// Empty tag <.../> // Empty tag <.../>
if (token == XML.SLASH) { if (token == XML.SLASH) {
if (x.nextToken() != XML.GT) { if (x.nextToken() != XML.GT) {
throw x.syntaxError("Misshaped tag"); throw x.syntaxError("Misshaped tag");
} }
if (ja == null) { if (ja == null) {
if (arrayForm) { if (arrayForm) {
return newja; return newja;
} else { } else {
return newjo; return newjo;
} }
} }
// Content, between <...> and </...> // Content, between <...> and </...>
} else { } else {
if (token != XML.GT) { if (token != XML.GT) {
throw x.syntaxError("Misshaped tag"); throw x.syntaxError("Misshaped tag");
} }
closeTag = (String)parse(x, arrayForm, newja); closeTag = (String)parse(x, arrayForm, newja);
if (closeTag != null) { if (closeTag != null) {
if (!closeTag.equals(tagName)) { if (!closeTag.equals(tagName)) {
throw x.syntaxError("Mismatched '" + tagName + throw x.syntaxError("Mismatched '" + tagName +
"' and '" + closeTag + "'"); "' and '" + closeTag + "'");
} }
tagName = null; tagName = null;
if (!arrayForm && newja.length() > 0) { if (!arrayForm && newja.length() > 0) {
newjo.put("childNodes", newja); newjo.put("childNodes", newja);
} }
if (ja == null) { if (ja == null) {
if (arrayForm) { if (arrayForm) {
return newja; return newja;
} else { } else {
return newjo; return newjo;
} }
} }
} }
} }
} }
} else { } else {
if (ja != null) { if (ja != null) {
ja.put(token instanceof String ? ja.put(token instanceof String ?
XML.stringToValue((String)token) : token); XML.stringToValue((String)token) : token);
} }
} }
} }
} }
@ -242,7 +242,7 @@ public class JSONML {
* @throws JSONException * @throws JSONException
*/ */
public static JSONArray toJSONArray(String string) throws JSONException { public static JSONArray toJSONArray(String string) throws JSONException {
return toJSONArray(new XMLTokener(string)); return toJSONArray(new XMLTokener(string));
} }
@ -259,16 +259,16 @@ public class JSONML {
* @throws JSONException * @throws JSONException
*/ */
public static JSONArray toJSONArray(XMLTokener x) throws JSONException { public static JSONArray toJSONArray(XMLTokener x) throws JSONException {
return (JSONArray)parse(x, true, null); return (JSONArray)parse(x, true, null);
} }
/** /**
* Convert a well-formed (but not necessarily valid) XML string into a * Convert a well-formed (but not necessarily valid) XML string into a
* JSONObject using the JsonML transform. Each XML tag is represented as * JSONObject using the JsonML transform. Each XML tag is represented as
* a JSONObject with a "tagName" property. If the tag has attributes, then * a JSONObject with a "tagName" property. If the tag has attributes, then
* the attributes will be in the JSONObject as properties. If the tag * the attributes will be in the JSONObject as properties. If the tag
* contains children, the object will have a "childNodes" property which * contains children, the object will have a "childNodes" property which
* will be an array of strings and JsonML JSONObjects. * will be an array of strings and JsonML JSONObjects.
* Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored. * Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored.
@ -277,16 +277,16 @@ public class JSONML {
* @throws JSONException * @throws JSONException
*/ */
public static JSONObject toJSONObject(XMLTokener x) throws JSONException { public static JSONObject toJSONObject(XMLTokener x) throws JSONException {
return (JSONObject)parse(x, false, null); return (JSONObject)parse(x, false, null);
} }
/** /**
* Convert a well-formed (but not necessarily valid) XML string into a * Convert a well-formed (but not necessarily valid) XML string into a
* JSONObject using the JsonML transform. Each XML tag is represented as * JSONObject using the JsonML transform. Each XML tag is represented as
* a JSONObject with a "tagName" property. If the tag has attributes, then * a JSONObject with a "tagName" property. If the tag has attributes, then
* the attributes will be in the JSONObject as properties. If the tag * the attributes will be in the JSONObject as properties. If the tag
* contains children, the object will have a "childNodes" property which * contains children, the object will have a "childNodes" property which
* will be an array of strings and JsonML JSONObjects. * will be an array of strings and JsonML JSONObjects.
* Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored. * Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored.
@ -295,7 +295,7 @@ public class JSONML {
* @throws JSONException * @throws JSONException
*/ */
public static JSONObject toJSONObject(String string) throws JSONException { public static JSONObject toJSONObject(String string) throws JSONException {
return toJSONObject(new XMLTokener(string)); return toJSONObject(new XMLTokener(string));
} }
@ -306,156 +306,156 @@ public class JSONML {
* @throws JSONException * @throws JSONException
*/ */
public static String toString(JSONArray ja) throws JSONException { public static String toString(JSONArray ja) throws JSONException {
int i; int i;
JSONObject jo; JSONObject jo;
String key; String key;
Iterator keys; Iterator keys;
int length; int length;
Object object; Object object;
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
String tagName; String tagName;
String value; String value;
// Emit <tagName // Emit <tagName
tagName = ja.getString(0); tagName = ja.getString(0);
XML.noSpace(tagName); XML.noSpace(tagName);
tagName = XML.escape(tagName); tagName = XML.escape(tagName);
sb.append('<'); sb.append('<');
sb.append(tagName); sb.append(tagName);
object = ja.opt(1); object = ja.opt(1);
if (object instanceof JSONObject) { if (object instanceof JSONObject) {
i = 2; i = 2;
jo = (JSONObject)object; jo = (JSONObject)object;
// Emit the attributes // Emit the attributes
keys = jo.keys(); keys = jo.keys();
while (keys.hasNext()) { while (keys.hasNext()) {
key = keys.next().toString(); key = keys.next().toString();
XML.noSpace(key); XML.noSpace(key);
value = jo.optString(key); value = jo.optString(key);
if (value != null) { if (value != null) {
sb.append(' '); sb.append(' ');
sb.append(XML.escape(key)); sb.append(XML.escape(key));
sb.append('='); sb.append('=');
sb.append('"'); sb.append('"');
sb.append(XML.escape(value)); sb.append(XML.escape(value));
sb.append('"'); sb.append('"');
} }
} }
} else { } else {
i = 1; i = 1;
} }
//Emit content in body //Emit content in body
length = ja.length(); length = ja.length();
if (i >= length) { if (i >= length) {
sb.append('/'); sb.append('/');
sb.append('>'); sb.append('>');
} else { } else {
sb.append('>'); sb.append('>');
do { do {
object = ja.get(i); object = ja.get(i);
i += 1; i += 1;
if (object != null) { if (object != null) {
if (object instanceof String) { if (object instanceof String) {
sb.append(XML.escape(object.toString())); sb.append(XML.escape(object.toString()));
} else if (object instanceof JSONObject) { } else if (object instanceof JSONObject) {
sb.append(toString((JSONObject)object)); sb.append(toString((JSONObject)object));
} else if (object instanceof JSONArray) { } else if (object instanceof JSONArray) {
sb.append(toString((JSONArray)object)); sb.append(toString((JSONArray)object));
} }
} }
} while (i < length); } while (i < length);
sb.append('<'); sb.append('<');
sb.append('/'); sb.append('/');
sb.append(tagName); sb.append(tagName);
sb.append('>'); sb.append('>');
} }
return sb.toString(); return sb.toString();
} }
/** /**
* Reverse the JSONML transformation, making an XML text from a JSONObject. * Reverse the JSONML transformation, making an XML text from a JSONObject.
* The JSONObject must contain a "tagName" property. If it has children, * The JSONObject must contain a "tagName" property. If it has children,
* then it must have a "childNodes" property containing an array of objects. * then it must have a "childNodes" property containing an array of objects.
* The other properties are attributes with string values. * The other properties are attributes with string values.
* @param jo A JSONObject. * @param jo A JSONObject.
* @return An XML string. * @return An XML string.
* @throws JSONException * @throws JSONException
*/ */
public static String toString(JSONObject jo) throws JSONException { public static String toString(JSONObject jo) throws JSONException {
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
int i; int i;
JSONArray ja; JSONArray ja;
String key; String key;
Iterator keys; Iterator keys;
int length; int length;
Object object; Object object;
String tagName; String tagName;
String value; String value;
//Emit <tagName //Emit <tagName
tagName = jo.optString("tagName"); tagName = jo.optString("tagName");
if (tagName == null) { if (tagName == null) {
return XML.escape(jo.toString()); return XML.escape(jo.toString());
} }
XML.noSpace(tagName); XML.noSpace(tagName);
tagName = XML.escape(tagName); tagName = XML.escape(tagName);
sb.append('<'); sb.append('<');
sb.append(tagName); sb.append(tagName);
//Emit the attributes //Emit the attributes
keys = jo.keys(); keys = jo.keys();
while (keys.hasNext()) { while (keys.hasNext()) {
key = keys.next().toString(); key = keys.next().toString();
if (!key.equals("tagName") && !key.equals("childNodes")) { if (!key.equals("tagName") && !key.equals("childNodes")) {
XML.noSpace(key); XML.noSpace(key);
value = jo.optString(key); value = jo.optString(key);
if (value != null) { if (value != null) {
sb.append(' '); sb.append(' ');
sb.append(XML.escape(key)); sb.append(XML.escape(key));
sb.append('='); sb.append('=');
sb.append('"'); sb.append('"');
sb.append(XML.escape(value)); sb.append(XML.escape(value));
sb.append('"'); sb.append('"');
} }
} }
} }
//Emit content in body //Emit content in body
ja = jo.optJSONArray("childNodes"); ja = jo.optJSONArray("childNodes");
if (ja == null) { if (ja == null) {
sb.append('/'); sb.append('/');
sb.append('>'); sb.append('>');
} else { } else {
sb.append('>'); sb.append('>');
length = ja.length(); length = ja.length();
for (i = 0; i < length; i += 1) { for (i = 0; i < length; i += 1) {
object = ja.get(i); object = ja.get(i);
if (object != null) { if (object != null) {
if (object instanceof String) { if (object instanceof String) {
sb.append(XML.escape(object.toString())); sb.append(XML.escape(object.toString()));
} else if (object instanceof Number) {
sb.append(object.toString());
} else if (object instanceof JSONObject) { } else if (object instanceof JSONObject) {
sb.append(toString((JSONObject)object)); sb.append(toString((JSONObject)object));
} else if (object instanceof JSONArray) { } else if (object instanceof JSONArray) {
sb.append(toString((JSONArray)object)); sb.append(toString((JSONArray)object));
} } else {
} sb.append(object.toString());
} }
sb.append('<'); }
sb.append('/'); }
sb.append(tagName); sb.append('<');
sb.append('>'); sb.append('/');
} sb.append(tagName);
sb.append('>');
}
return sb.toString(); return sb.toString();
} }
} }