1
0
Fork 0
mirror of https://github.com/ethauvin/JSON-java.git synced 2025-06-17 07:50:52 -07:00

Formatting

This commit is contained in:
John J. Aylward 2015-10-26 18:35:40 -04:00
parent 7886c96204
commit 105426b53f

228
XML.java
View file

@ -27,49 +27,54 @@ SOFTWARE.
import java.util.Iterator; import java.util.Iterator;
/** /**
* This provides static methods to convert an XML text into a JSONObject, * This provides static methods to convert an XML text into a JSONObject, and to
* and to covert a JSONObject into an XML text. * covert a JSONObject into an XML text.
*
* @author JSON.org * @author JSON.org
* @version 2015-10-18 * @version 2015-10-18
*/ */
@SuppressWarnings("boxing")
public class XML { public class XML {
/** The Character '&'. */ /** The Character '&'. */
public static final Character AMP = '&'; public static final Character AMP = '&';
/** The Character '''. */ /** The Character '''. */
public static final Character APOS = '\''; public static final Character APOS = '\'';
/** The Character '!'. */ /** The Character '!'. */
public static final Character BANG = '!'; public static final Character BANG = '!';
/** The Character '='. */ /** The Character '='. */
public static final Character EQ = '='; public static final Character EQ = '=';
/** The Character '>'. */ /** The Character '>'. */
public static final Character GT = '>'; public static final Character GT = '>';
/** The Character '<'. */ /** The Character '<'. */
public static final Character LT = '<'; public static final Character LT = '<';
/** The Character '?'. */ /** The Character '?'. */
public static final Character QUEST = '?'; public static final Character QUEST = '?';
/** The Character '"'. */ /** The Character '"'. */
public static final Character QUOT = '"'; public static final Character QUOT = '"';
/** The Character '/'. */ /** The Character '/'. */
public static final Character SLASH = '/'; public static final Character SLASH = '/';
/** /**
* Replace special characters with XML escapes: * Replace special characters with XML escapes:
*
* <pre> * <pre>
* &amp; <small>(ampersand)</small> is replaced by &amp;amp; * &amp; <small>(ampersand)</small> is replaced by &amp;amp;
* &lt; <small>(less than)</small> is replaced by &amp;lt; * &lt; <small>(less than)</small> is replaced by &amp;lt;
* &gt; <small>(greater than)</small> is replaced by &amp;gt; * &gt; <small>(greater than)</small> is replaced by &amp;gt;
* &quot; <small>(double quote)</small> is replaced by &amp;quot; * &quot; <small>(double quote)</small> is replaced by &amp;quot;
* </pre> * </pre>
* @param string The string to be escaped. *
* @param string
* The string to be escaped.
* @return The escaped string. * @return The escaped string.
*/ */
public static String escape(String string) { public static String escape(String string) {
@ -100,9 +105,11 @@ public class XML {
} }
/** /**
* Throw an exception if the string contains whitespace. * Throw an exception if the string contains whitespace. Whitespace is not
* Whitespace is not allowed in tagNames and attributes. * allowed in tagNames and attributes.
* @param string A string. *
* @param string
* A string.
* @throws JSONException * @throws JSONException
*/ */
public static void noSpace(String string) throws JSONException { public static void noSpace(String string) throws JSONException {
@ -112,42 +119,46 @@ public class XML {
} }
for (i = 0; i < length; i += 1) { for (i = 0; i < length; i += 1) {
if (Character.isWhitespace(string.charAt(i))) { if (Character.isWhitespace(string.charAt(i))) {
throw new JSONException("'" + string + throw new JSONException("'" + string
"' contains a space character."); + "' contains a space character.");
} }
} }
} }
/** /**
* Scan the content following the named tag, attaching it to the context. * Scan the content following the named tag, attaching it to the context.
* @param x The XMLTokener containing the source string. *
* @param context The JSONObject that will include the new material. * @param x
* @param name The tag name. * The XMLTokener containing the source string.
* @param context
* The JSONObject that will include the new material.
* @param name
* The tag name.
* @return true if the close tag is processed. * @return true if the close tag is processed.
* @throws JSONException * @throws JSONException
*/ */
private static boolean parse(XMLTokener x, JSONObject context, private static boolean parse(XMLTokener x, JSONObject context, String name)
String name) throws JSONException { throws JSONException {
char c; char c;
int i; int i;
JSONObject jsonobject = null; JSONObject jsonobject = null;
String string; String string;
String tagName; String tagName;
Object token; Object token;
// Test for and skip past these forms: // Test for and skip past these forms:
// <!-- ... --> // <!-- ... -->
// <! ... > // <! ... >
// <![ ... ]]> // <![ ... ]]>
// <? ... ?> // <? ... ?>
// Report errors for these forms: // Report errors for these forms:
// <> // <>
// <= // <=
// << // <<
token = x.nextToken(); token = x.nextToken();
// <! // <!
if (token == BANG) { if (token == BANG) {
c = x.next(); c = x.next();
@ -184,13 +195,12 @@ public class XML {
return false; return false;
} else if (token == QUEST) { } else if (token == QUEST) {
// <? // <?
x.skipPast("?>"); x.skipPast("?>");
return false; return false;
} else if (token == SLASH) { } else if (token == SLASH) {
// Close tag </ // Close tag </
token = x.nextToken(); token = x.nextToken();
if (name == null) { if (name == null) {
@ -207,10 +217,10 @@ public class XML {
} else if (token instanceof Character) { } else if (token instanceof Character) {
throw x.syntaxError("Misshaped tag"); throw x.syntaxError("Misshaped tag");
// Open tag < // Open tag <
} else { } else {
tagName = (String)token; tagName = (String) token;
token = null; token = null;
jsonobject = new JSONObject(); jsonobject = new JSONObject();
for (;;) { for (;;) {
@ -218,10 +228,9 @@ public class XML {
token = x.nextToken(); token = x.nextToken();
} }
// attribute = value // attribute = value
if (token instanceof String) { if (token instanceof String) {
string = (String)token; string = (String) token;
token = x.nextToken(); token = x.nextToken();
if (token == EQ) { if (token == EQ) {
token = x.nextToken(); token = x.nextToken();
@ -229,15 +238,15 @@ public class XML {
throw x.syntaxError("Missing value"); throw x.syntaxError("Missing value");
} }
jsonobject.accumulate(string, jsonobject.accumulate(string,
XML.stringToValue((String)token)); XML.stringToValue((String) token));
token = null; token = null;
} else { } else {
jsonobject.accumulate(string, ""); jsonobject.accumulate(string, "");
} }
// Empty tag <.../>
} else if (token == SLASH) { } else if (token == SLASH) {
// Empty tag <.../>
if (x.nextToken() != GT) { if (x.nextToken() != GT) {
throw x.syntaxError("Misshaped tag"); throw x.syntaxError("Misshaped tag");
} }
@ -248,9 +257,8 @@ public class XML {
} }
return false; return false;
// Content, between <...> and </...>
} else if (token == GT) { } else if (token == GT) {
// Content, between <...> and </...>
for (;;) { for (;;) {
token = x.nextContent(); token = x.nextContent();
if (token == null) { if (token == null) {
@ -259,20 +267,19 @@ public class XML {
} }
return false; return false;
} else if (token instanceof String) { } else if (token instanceof String) {
string = (String)token; string = (String) token;
if (string.length() > 0) { if (string.length() > 0) {
jsonobject.accumulate("content", jsonobject.accumulate("content",
XML.stringToValue(string)); XML.stringToValue(string));
} }
// Nested element
} else if (token == LT) { } else if (token == LT) {
// Nested element
if (parse(x, jsonobject, tagName)) { if (parse(x, jsonobject, tagName)) {
if (jsonobject.length() == 0) { if (jsonobject.length() == 0) {
context.accumulate(tagName, ""); context.accumulate(tagName, "");
} else if (jsonobject.length() == 1 && } else if (jsonobject.length() == 1
jsonobject.opt("content") != null) { && jsonobject.opt("content") != null) {
context.accumulate(tagName, context.accumulate(tagName,
jsonobject.opt("content")); jsonobject.opt("content"));
} else { } else {
@ -289,14 +296,15 @@ public class XML {
} }
} }
/** /**
* Try to convert a string into a number, boolean, or null. If the string * Try to convert a string into a number, boolean, or null. If the string
* can't be converted, return the string. This is much less ambitious than * can't be converted, return the string. This is much less ambitious than
* JSONObject.stringToValue, especially because it does not attempt to * JSONObject.stringToValue, especially because it does not attempt to
* convert plus forms, octal forms, hex forms, or E forms lacking decimal * convert plus forms, octal forms, hex forms, or E forms lacking decimal
* points. * points.
* @param string A String. *
* @param string
* A String.
* @return A simple JSON value. * @return A simple JSON value.
*/ */
public static Object stringToValue(String string) { public static Object stringToValue(String string) {
@ -310,9 +318,8 @@ public class XML {
return JSONObject.NULL; return JSONObject.NULL;
} }
// If it might be a number, try converting it, first as a Long, and then as a // If it might be a number, try converting it, first as a Long, and then
// Double. If that doesn't work, return the string. // as a Double. If that doesn't work, return the string.
try { try {
char initial = string.charAt(0); char initial = string.charAt(0);
if (initial == '-' || (initial >= '0' && initial <= '9')) { if (initial == '-' || (initial >= '0' && initial <= '9')) {
@ -321,30 +328,31 @@ public class XML {
return value; return value;
} }
} }
} catch (Exception ignore) { } catch (Exception ignore) {
try { try {
Double value = new Double(string); Double value = new Double(string);
if (value.toString().equals(string)) { if (value.toString().equals(string)) {
return value; return value;
} }
} catch (Exception ignoreAlso) { } catch (Exception ignoreAlso) {
} }
} }
return string; return string;
} }
/** /**
* 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. Some information may be lost in this transformation * JSONObject. Some information may be lost in this transformation because
* because JSON is a data format and XML is a document format. XML uses * JSON is a data format and XML is a document format. XML uses elements,
* elements, attributes, and content text, while JSON uses unordered * attributes, and content text, while JSON uses unordered collections of
* collections of name/value pairs and arrays of values. JSON does not * name/value pairs and arrays of values. JSON does not does not like to
* does not like to distinguish between elements and attributes. * distinguish between elements and attributes. Sequences of similar
* Sequences of similar elements are represented as JSONArrays. Content * elements are represented as JSONArrays. Content text may be placed in a
* text may be placed in a "content" member. Comments, prologs, DTDs, and * "content" member. Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code>
* <code>&lt;[ [ ]]></code> are ignored. * are ignored.
* @param string The source string. *
* @param string
* The source string.
* @return A JSONObject containing the structured data from the XML string. * @return A JSONObject containing the structured data from the XML string.
* @throws JSONException * @throws JSONException
*/ */
@ -357,65 +365,64 @@ public class XML {
return jo; return jo;
} }
/** /**
* Convert a JSONObject into a well-formed, element-normal XML string. * Convert a JSONObject into a well-formed, element-normal XML string.
* @param object A JSONObject. *
* @return A string. * @param object
* @throws JSONException * A JSONObject.
* @return A string.
* @throws JSONException
*/ */
public static String toString(Object object) throws JSONException { public static String toString(Object object) throws JSONException {
return toString(object, null); return toString(object, null);
} }
/** /**
* Convert a JSONObject into a well-formed, element-normal XML string. * Convert a JSONObject into a well-formed, element-normal XML string.
* @param object A JSONObject. *
* @param tagName The optional name of the enclosing tag. * @param object
* A JSONObject.
* @param tagName
* The optional name of the enclosing tag.
* @return A string. * @return A string.
* @throws JSONException * @throws JSONException
*/ */
public static String toString(Object object, String tagName) public static String toString(Object object, String tagName)
throws JSONException { throws JSONException {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
JSONArray ja; JSONArray ja;
JSONObject jo; JSONObject jo;
String key; String key;
Iterator<String> keys; Iterator<String> keys;
String string; String string;
Object value; Object value;
if (object instanceof JSONObject) { if (object instanceof JSONObject) {
// Emit <tagName> // Emit <tagName>
if (tagName != null) { if (tagName != null) {
sb.append('<'); sb.append('<');
sb.append(tagName); sb.append(tagName);
sb.append('>'); sb.append('>');
} }
// Loop thru the keys. // Loop thru the keys.
jo = (JSONObject) object;
jo = (JSONObject)object;
keys = jo.keys(); keys = jo.keys();
while (keys.hasNext()) { while (keys.hasNext()) {
key = keys.next(); key = keys.next();
value = jo.opt(key); value = jo.opt(key);
if (value == null) { if (value == null) {
value = ""; value = "";
}else if(value.getClass().isArray()){ } else if (value.getClass().isArray()) {
value = new JSONArray(value); value = new JSONArray(value);
} }
string = value instanceof String ? (String)value : null; string = value instanceof String ? (String) value : null;
// Emit content in body
// Emit content in body
if ("content".equals(key)) { if ("content".equals(key)) {
if (value instanceof JSONArray) { if (value instanceof JSONArray) {
ja = (JSONArray)value; ja = (JSONArray) value;
int i = 0; int i = 0;
for (Object val : ja) { for (Object val : ja) {
if (i > 0) { if (i > 0) {
@ -428,10 +435,10 @@ public class XML {
sb.append(escape(value.toString())); sb.append(escape(value.toString()));
} }
// Emit an array of similar keys // Emit an array of similar keys
} else if (value instanceof JSONArray) { } else if (value instanceof JSONArray) {
ja = (JSONArray)value; ja = (JSONArray) value;
for (Object val : ja) { for (Object val : ja) {
if (val instanceof JSONArray) { if (val instanceof JSONArray) {
sb.append('<'); sb.append('<');
@ -450,7 +457,7 @@ public class XML {
sb.append(key); sb.append(key);
sb.append("/>"); sb.append("/>");
// Emit a new tag <k> // Emit a new tag <k>
} else { } else {
sb.append(toString(value, key)); sb.append(toString(value, key));
@ -458,35 +465,36 @@ public class XML {
} }
if (tagName != null) { if (tagName != null) {
// Emit the </tagname> close tag // Emit the </tagname> close tag
sb.append("</"); sb.append("</");
sb.append(tagName); sb.append(tagName);
sb.append('>'); sb.append('>');
} }
return sb.toString(); return sb.toString();
// XML does not have good support for arrays. If an array appears in a place
// where XML is lacking, synthesize an <array> element.
} }
if(object!=null){
if (object != null) {
if (object.getClass().isArray()) { if (object.getClass().isArray()) {
object = new JSONArray(object); object = new JSONArray(object);
} }
if (object instanceof JSONArray) { if (object instanceof JSONArray) {
ja = (JSONArray)object; ja = (JSONArray) object;
for (Object val : ja) { for (Object val : ja) {
// XML does not have good support for arrays. If an array
// appears in a place where XML is lacking, synthesize an
// <array> element.
sb.append(toString(val, tagName == null ? "array" : tagName)); sb.append(toString(val, tagName == null ? "array" : tagName));
} }
return sb.toString(); return sb.toString();
} }
} }
string = (object == null) ? "null" : escape(object.toString()); string = (object == null) ? "null" : escape(object.toString());
return (tagName == null) ? "\"" + string + "\"" : return (tagName == null) ? "\"" + string + "\""
(string.length() == 0) ? "<" + tagName + "/>" : : (string.length() == 0) ? "<" + tagName + "/>" : "<" + tagName
"<" + tagName + ">" + string + "</" + tagName + ">"; + ">" + string + "</" + tagName + ">";
} }
} }