map,xml互转

1.这个转出来会有很多空格

package cn.paypalm.platform.sdk.util;

import java.lang.reflect.Field;
import java.util.Collection;
import java.util.Map;
import java.util.Set;

/**
* The Class MapToXMLString.
*
* @author zhangsl 20140623
*/
public class MapToXMLString {

/**
* Converter Map instance to xml string. Note: currently,
* we aren't consider more about some collection types, such as array,list,
*
* @param dataMapthe data map
*
* @return the string
*/
public static String converterPayPalm(Map dataMap)
{
synchronized (MapToXMLString.class)
{
StringBuilder strBuilder = new StringBuilder();
strBuilder.append("");
strBuilder.append("【map,xml互转】");
Set objSet = dataMap.keySet();
for (Object key : objSet)
{
if (key == null)
{
continue;
}
strBuilder.append("\n");
strBuilder.append("<").append(key.toString()).append(">\n");
Object value = https://www.it610.com/article/dataMap.get(key);
strBuilder.append(coverter(value).trim());
strBuilder.append("\n");
}
strBuilder.append("");
return strBuilder.toString();
}
}

/**
* Converter Map instance to xml string. Note: currently,
* we aren't consider more about some collection types, such as array,list,
*
* @param dataMapthe data map
*
* @return the string
*/
public static String converter(Map dataMap, String xmlRootStart, String xmlRootEnd)
{
synchronized (MapToXMLString.class)
{
StringBuilder strBuilder = new StringBuilder();
strBuilder.append(xmlRootStart);
Set objSet = dataMap.keySet();
for (Object key : objSet)
{
if (key == null)
{
continue;
}
strBuilder.append("\n");
strBuilder.append("<").append(key.toString()).append(">\n");
Object value = https://www.it610.com/article/dataMap.get(key);
strBuilder.append(coverter(value));
strBuilder.append("\n");
}
strBuilder.append(xmlRootEnd);
return strBuilder.toString();
}
}

public static String coverter(Object[] objects) {
StringBuilder strBuilder = new StringBuilder();
for(Object obj:objects) {
strBuilder.append("\n");
strBuilder.append(coverter(obj));
strBuilder.append("
\n");
}
return strBuilder.toString();
}

public static String coverter(Collection objects)
{
StringBuilder strBuilder = new StringBuilder();
for(Object obj:objects) {
strBuilder.append("\n");
strBuilder.append(coverter(obj));
strBuilder.append("
\n");
}
return strBuilder.toString();
}

/**
* Coverter.
*
* @param object the object
* @return the string
*/
public static String coverter(Object object)
{
if (object instanceof Object[])
{
return coverter((Object[]) object);
}
if (object instanceof Collection)
{
return coverter((Collection) object);
}
StringBuilder strBuilder = new StringBuilder();
if (isObject(object))
{
Class clz = object.getClass();
Field[] fields = clz.getDeclaredFields();

for (Field field : fields)
{
field.setAccessible(true);
if (field == null)
{
continue;
}
String fieldName = field.getName();
Object value = https://www.it610.com/article/null;
try
{
value = https://www.it610.com/article/field.get(object);
}
catch (IllegalArgumentException e)
{
continue;
}
catch (IllegalAccessException e)
{
continue;
}
strBuilder.append("<").append(fieldName)
.append(" className=\"").append(
value.getClass().getName()).append("\">\n");
if (isObject(value))
{
strBuilder.append(coverter(value));
}
else if (value =https://www.it610.com/article/= null)
{
strBuilder.append("null\n");
}
else
{
strBuilder.append(value.toString() + "\n");
}
strBuilder.append("\n");
}
}
else if (object == null)
{
strBuilder.append("null\n");
}
else
{
strBuilder.append(object.toString() + "\n");
}
return strBuilder.toString();
}

/**
* Checks if is object.
*
* @param obj the obj
*
* @return true, if is object
*/
private static boolean isObject(Object obj)
{
if (obj == null)
{
return false;
}
if (obj instanceof String)
{
return false;
}
if (obj instanceof Integer)
{
return false;
}
if (obj instanceof Double)
{
return false;
}
if (obj instanceof Float)
{
return false;
}
if (obj instanceof Byte)
{
return false;
}
if (obj instanceof Long)
{
return false;
}
if (obj instanceof Character)
{
return false;
}
if (obj instanceof Short)
{
return false;
}
if (obj instanceof Boolean)
{
return false;
}
return true;
}

}

2.此用法出来的很正规,因为我不用xml中写type类型,所以自已改了原代码
Map2XML xmlSerializer = new Map2XML();
String reqData = https://www.it610.com/article/xmlSerializer.write(JSONObject.fromObject(map));


/*jadclipse*/// Decompiled by Jad v1.5.8f. Copyright 2001 Pavel Kouznetsov.

package net.sf.json.xml;

import java.io.*;
import java.util.*;
import net.sf.json.*;
import net.sf.json.util.JSONUtils;
import nu.xom.*;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class Map2XML
{
private class XomSerializer extends Serializer
{

protected void write(Text text)
throws IOException
{
String value = https://www.it610.com/article/text.getValue();
if(value.startsWith(""))
{
value = https://www.it610.com/article/value.substring(9);
value = https://www.it610.com/article/value.substring(0, value.length() - 3);
writeRaw("writeRaw(value);
writeRaw("]]>");
} else
{
super.write(text);
}
}

protected void writeEmptyElementTag(Element element)
throws IOException
{
if((element instanceof CustomElement) && isNamespaceLenient())
{
writeTagBeginning((CustomElement)element);
writeRaw("/>");
} else
{
super.writeEmptyElementTag(element);
}
}

protected void writeEndTag(Element element)
throws IOException
{
if((element instanceof CustomElement) && isNamespaceLenient())
{
writeRaw("writeRaw(((CustomElement)element).getQName());
writeRaw(">");
} else
{
super.writeEndTag(element);
}
}

protected void writeNamespaceDeclaration(String prefix, String uri)
throws IOException
{
if(!StringUtils.isBlank(uri))
super.writeNamespaceDeclaration(prefix, uri);
}

protected void writeStartTag(Element element)
throws IOException
{
if((element instanceof CustomElement) && isNamespaceLenient())
{
writeTagBeginning((CustomElement)element);
writeRaw(">");
} else
{
super.writeStartTag(element);
}
}

private void writeTagBeginning(CustomElement element)
throws IOException
{
writeRaw("<");
writeRaw(element.getQName());
writeAttributes(element);
writeNamespaceDeclarations(element);
}

public XomSerializer(OutputStream out)
{
super(out);
}

public XomSerializer(OutputStream out, String encoding)
throws UnsupportedEncodingException
{
super(out, encoding);
}
}

private static class CustomElement extends Element
{

private static String getName(String name)
{
int colon = name.indexOf(':');
if(colon != -1)
return name.substring(colon + 1);
else
return name;
}

private static String getPrefix(String name)
{
int colon = name.indexOf(':');
if(colon != -1)
return name.substring(0, colon);
else
return "";
}

public final String getQName()
{
if(prefix.length() == 0)
return getLocalName();
else
return prefix + ":" + getLocalName();
}

private String prefix;

public CustomElement(String name)
{
super(getName(name));
prefix = getPrefix(name);
}
}


public Map2XML()
{
namespacesPerElement = new TreeMap();
rootNamespace = new TreeMap();
setObjectName("o");
setArrayName("a");
setElementName("e");
setTypeHintsEnabled(true);
setTypeHintsCompatibility(true);
setNamespaceLenient(false);
setSkipNamespaces(false);
setRemoveNamespacePrefixFromElements(false);
setTrimSpaces(false);
setExpandableProperties(EMPTY_ARRAY);
setSkipNamespaces(false);
}

public void addNamespace(String prefix, String uri)
{
addNamespace(prefix, uri, null);
}

public void addNamespace(String prefix, String uri, String elementName)
{
if(StringUtils.isBlank(uri))
return;
if(prefix == null)
prefix = "";
if(StringUtils.isBlank(elementName))
{
rootNamespace.put(prefix.trim(), uri.trim());
} else
{
Map nameSpaces = (Map)namespacesPerElement.get(elementName);
if(nameSpaces == null)
{
nameSpaces = new TreeMap();
namespacesPerElement.put(elementName, nameSpaces);
}
nameSpaces.put(prefix, uri);
}
}

public void clearNamespaces()
{
rootNamespace.clear();
namespacesPerElement.clear();
}

public void clearNamespaces(String elementName)
{
if(StringUtils.isBlank(elementName))
rootNamespace.clear();
else
namespacesPerElement.remove(elementName);
}

public String getArrayName()
{
return arrayName;
}

public String getElementName()
{
return elementName;
}

public String[] getExpandableProperties()
{
return expandableProperties;
}

public String getObjectName()
{
return objectName;
}

public String getRootName()
{
return rootName;
}

public boolean isForceTopLevelObject()
{
return forceTopLevelObject;
}

public boolean isNamespaceLenient()
{
return namespaceLenient;
}

public boolean isRemoveNamespacePrefixFromElements()
{
return removeNamespacePrefixFromElements;
}

public boolean isSkipNamespaces()
{
return skipNamespaces;
}

public boolean isSkipWhitespace()
{
return skipWhitespace;
}

public boolean isTrimSpaces()
{
return trimSpaces;
}

public boolean isTypeHintsCompatibility()
{
return typeHintsCompatibility;
}

public boolean isTypeHintsEnabled()
{
return typeHintsEnabled;
}

public JSON read(String xml) throws ValidityException, ParsingException, IOException
{
JSON json = null;
Element root;
Document doc = (new Builder()).build(new StringReader(xml));
root = doc.getRootElement();
if(isNullObject(root))
return JSONNull.getInstance();
try
{
String defaultType = getType(root, "string");
if(isArray(root, true))
{
json = processArrayElement(root, defaultType);
if(forceTopLevelObject)
{
String key = removeNamespacePrefix(root.getQualifiedName());
json = (new JSONObject()).element(key, json);
}
} else
{
json = processObjectElement(root, defaultType);
if(forceTopLevelObject)
{
String key = removeNamespacePrefix(root.getQualifiedName());
json = (new JSONObject()).element(key, json);
}
}
}
catch(JSONException jsone)
{
throw jsone;
}
catch(Exception e)
{
throw new JSONException(e);
}
return json;
}

public JSON readFromFile(File file) throws ValidityException, ParsingException, IOException
{
if(file == null)
throw new JSONException("File is null");
if(!file.canRead())
throw new JSONException("Can't read input file");
if(file.isDirectory())
throw new JSONException("File is a directory");
return readFromStream(new FileInputStream(file));

}

public JSON readFromFile(String path) throws ValidityException, ParsingException, IOException
{
return readFromStream(Thread.currentThread().getContextClassLoader().getResourceAsStream(path));
}

public JSON readFromStream(InputStream stream) throws ValidityException, ParsingException, IOException
{
StringBuffer xml;
xml = new StringBuffer();
BufferedReader in = new BufferedReader(new InputStreamReader(stream));
for(String line = null; (line = in.readLine()) != null; )
xml.append(line);

return read(xml.toString());
}

public void removeNamespace(String prefix)
{
removeNamespace(prefix, null);
}

public void removeNamespace(String prefix, String elementName)
{
if(prefix == null)
prefix = "";
if(StringUtils.isBlank(elementName))
{
rootNamespace.remove(prefix.trim());
} else
{
Map nameSpaces = (Map)namespacesPerElement.get(elementName);
nameSpaces.remove(prefix);
}
}

public void setArrayName(String arrayName)
{
this.arrayName = StringUtils.isBlank(arrayName) ? "a" : arrayName;
}

public void setElementName(String elementName)
{
this.elementName = StringUtils.isBlank(elementName) ? "e" : elementName;
}

public void setExpandableProperties(String expandableProperties[])
{
this.expandableProperties = expandableProperties != null ? expandableProperties : EMPTY_ARRAY;
}

public void setForceTopLevelObject(boolean forceTopLevelObject)
{
this.forceTopLevelObject = forceTopLevelObject;
}

public void setNamespace(String prefix, String uri)
{
setNamespace(prefix, uri, null);
}

public void setNamespace(String prefix, String uri, String elementName)
{
if(StringUtils.isBlank(uri))
return;
if(prefix == null)
prefix = "";
if(StringUtils.isBlank(elementName))
{
rootNamespace.clear();
rootNamespace.put(prefix.trim(), uri.trim());
} else
{
Map nameSpaces = (Map)namespacesPerElement.get(elementName);
if(nameSpaces == null)
{
nameSpaces = new TreeMap();
namespacesPerElement.put(elementName, nameSpaces);
}
nameSpaces.clear();
nameSpaces.put(prefix, uri);
}
}

public void setNamespaceLenient(boolean namespaceLenient)
{
this.namespaceLenient = namespaceLenient;
}

public void setObjectName(String objectName)
{
this.objectName = StringUtils.isBlank(objectName) ? "o" : objectName;
}

public void setRemoveNamespacePrefixFromElements(boolean removeNamespacePrefixFromElements)
{
this.removeNamespacePrefixFromElements = removeNamespacePrefixFromElements;
}

public void setRootName(String rootName)
{
this.rootName = StringUtils.isBlank(rootName) ? null : rootName;
}

public void setSkipNamespaces(boolean skipNamespaces)
{
this.skipNamespaces = skipNamespaces;
}

public void setSkipWhitespace(boolean skipWhitespace)
{
this.skipWhitespace = skipWhitespace;
}

public void setTrimSpaces(boolean trimSpaces)
{
this.trimSpaces = trimSpaces;
}

public void setTypeHintsCompatibility(boolean typeHintsCompatibility)
{
this.typeHintsCompatibility = typeHintsCompatibility;
}

public void setTypeHintsEnabled(boolean typeHintsEnabled)
{
this.typeHintsEnabled = typeHintsEnabled;
}

public String write(JSON json)
{
return write(json, null);
}

public String write(JSON json, String encoding)
{
if(JSONNull.getInstance().equals(json))
{
Element root = null;
root = newElement(getRootName() != null ? getRootName() : getObjectName());
root.addAttribute(new Attribute(addJsonPrefix("null"), "true"));
Document doc = new Document(root);
return writeDocument(doc, encoding);
}
Element root;
Document doc;
if(json instanceof JSONArray)
{
JSONArray jsonArray = (JSONArray)json;
root = processJSONArray(jsonArray, newElement(getRootName() != null ? getRootName() : getArrayName()), expandableProperties);
doc = new Document(root);
return writeDocument(doc, encoding);
}
JSONObject jsonObject = (JSONObject)json;
root = null;
if(jsonObject.isNullObject())
{
root = newElement(getObjectName());
root.addAttribute(new Attribute(addJsonPrefix("null"), "true"));
} else
{
root = processJSONObject(jsonObject, newElement(getRootName() != null ? getRootName() : getObjectName()), expandableProperties, true);
}
doc = new Document(root);
return writeDocument(doc, encoding);
}

private String addJsonPrefix(String str)
{
if(!isTypeHintsCompatibility())
return "json_" + str;
else
return str;
}

private void addNameSpaceToElement(Element element)
{
String elementName = null;
if(element instanceof CustomElement)
elementName = ((CustomElement)element).getQName();
else
elementName = element.getQualifiedName();
Map nameSpaces = (Map)namespacesPerElement.get(elementName);
if(nameSpaces != null && !nameSpaces.isEmpty())
{
setNamespaceLenient(true);
for(Iterator entries = nameSpaces.entrySet().iterator(); entries.hasNext(); )
{
java.util.Map.Entry entry = (java.util.Map.Entry)entries.next();
String prefix = (String)entry.getKey();
String uri = (String)entry.getValue();
if(StringUtils.isBlank(prefix))
element.setNamespaceURI(uri);
else
element.addNamespaceDeclaration(prefix, uri);
}

}
}

private boolean checkChildElements(Element element, boolean isTopLevel)
{
int childCount = element.getChildCount();
Elements elements = element.getChildElements();
int elementCount = elements.size();
if(childCount == 1 && (element.getChild(0) instanceof Text))
return isTopLevel;
if(childCount == elementCount)
{
if(elementCount == 0)
return true;
if(elementCount == 1)
return skipWhitespace || (element.getChild(0) instanceof Text);
}
if(childCount > elementCount)
{
for(int i = 0; i < childCount; i++)
{
nu.xom.Node node = element.getChild(i);
if(!(node instanceof Text))
continue;
Text text = (Text)node;
if(StringUtils.isNotBlank(StringUtils.strip(text.getValue())) && !skipWhitespace)
return false;
}

}
String childName = elements.get(0).getQualifiedName();
for(int i = 1; i < elementCount; i++)
if(childName.compareTo(elements.get(i).getQualifiedName()) != 0)
return false;

return true;
}

private String getClass(Element element)
{
Attribute attribute = element.getAttribute(addJsonPrefix("class"));
String clazz = null;
if(attribute != null)
{
String clazzText = attribute.getValue().trim();
if("object".compareToIgnoreCase(clazzText) == 0)
clazz = "object";
else
if("array".compareToIgnoreCase(clazzText) == 0)
clazz = "array";
}
return clazz;
}

private String getType(Element element)
{
return getType(element, null);
}

private String getType(Element element, String defaultType)
{
//Attribute attribute = element.getAttribute(addJsonPrefix("type"));
//String type = null;
//if(attribute != null)
//{
//String typeText = attribute.getValue().trim();
//if("boolean".compareToIgnoreCase(typeText) == 0)
//type = "boolean";
//else
//if("number".compareToIgnoreCase(typeText) == 0)
//type = "number";
//else
//if("integer".compareToIgnoreCase(typeText) == 0)
//type = "integer";
//else
//if("float".compareToIgnoreCase(typeText) == 0)
//type = "float";
//else
//if("object".compareToIgnoreCase(typeText) == 0)
//type = "object";
//else
//if("array".compareToIgnoreCase(typeText) == 0)
//type = "array";
//else
//if("string".compareToIgnoreCase(typeText) == 0)
//type = "string";
//else
//if("function".compareToIgnoreCase(typeText) == 0)
//type = "function";
//} else
//if(defaultType != null)
//{
//log.info("Using default type " + defaultType);
//type = defaultType;
//}
//return type;
return null;
}

private boolean hasNamespaces(Element element)
{
int namespaces = 0;
for(int i = 0; i < element.getNamespaceDeclarationCount(); i++)
{
String prefix = element.getNamespacePrefix(i);
String uri = element.getNamespaceURI(prefix);
if(!StringUtils.isBlank(uri))
namespaces++;
}

return namespaces > 0;
}

private boolean isArray(Element element, boolean isTopLevel)
{
boolean isArray = false;
String clazz = getClass(element);
if(clazz != null && clazz.equals("array"))
isArray = true;
else
if(element.getAttributeCount() == 0)
isArray = checkChildElements(element, isTopLevel);
else
if(element.getAttributeCount() == 1 && (element.getAttribute(addJsonPrefix("class")) != null || element.getAttribute(addJsonPrefix("type")) != null))
isArray = checkChildElements(element, isTopLevel);
else
if(element.getAttributeCount() == 2 && element.getAttribute(addJsonPrefix("class")) != null && element.getAttribute(addJsonPrefix("type")) != null)
isArray = checkChildElements(element, isTopLevel);
if(isArray)
{
for(int j = 0; j < element.getNamespaceDeclarationCount(); j++)
{
String prefix = element.getNamespacePrefix(j);
String uri = element.getNamespaceURI(prefix);
if(!StringUtils.isBlank(uri))
return false;
}

}
return isArray;
}

private boolean isFunction(Element element)
{
int attrCount = element.getAttributeCount();
if(attrCount > 0)
{
Attribute typeAttr = element.getAttribute(addJsonPrefix("type"));
Attribute paramsAttr = element.getAttribute(addJsonPrefix("params"));
if(attrCount == 1 && paramsAttr != null)
return true;
if(attrCount == 2 && paramsAttr != null && typeAttr != null && (typeAttr.getValue().compareToIgnoreCase("string") == 0 || typeAttr.getValue().compareToIgnoreCase("function") == 0))
return true;
}
return false;
}

private boolean isNullObject(Element element)
{
if(element.getChildCount() == 0)
{
if(element.getAttributeCount() == 0)
return true;
if(element.getAttribute(addJsonPrefix("null")) != null)
return true;
if(element.getAttributeCount() == 1 && (element.getAttribute(addJsonPrefix("class")) != null || element.getAttribute(addJsonPrefix("type")) != null))
return true;
if(element.getAttributeCount() == 2 && element.getAttribute(addJsonPrefix("class")) != null && element.getAttribute(addJsonPrefix("type")) != null)
return true;
}
return skipWhitespace && element.getChildCount() == 1 && (element.getChild(0) instanceof Text);
}

private boolean isObject(Element element, boolean isTopLevel)
{
boolean isObject = false;
if(!isArray(element, isTopLevel) && !isFunction(element))
{
if(hasNamespaces(element))
return true;
int attributeCount = element.getAttributeCount();
if(attributeCount > 0)
{
int attrs = element.getAttribute(addJsonPrefix("null")) != null ? 1 : 0;
attrs += element.getAttribute(addJsonPrefix("class")) != null ? 1 : 0;
attrs += element.getAttribute(addJsonPrefix("type")) != null ? 1 : 0;
switch(attributeCount)
{
case 1: // '\001'
if(attrs == 0)
return true;
break;

case 2: // '\002'
if(attrs < 2)
return true;
break;

case 3: // '\003'
if(attrs < 3)
return true;
break;

default:
return true;
}
}
int childCount = element.getChildCount();
if(childCount == 1 && (element.getChild(0) instanceof Text))
return isTopLevel;
isObject = true;
}
return isObject;
}

private Element newElement(String name)
{
if(name.indexOf(':') != -1)
namespaceLenient = true;
return ((Element) (namespaceLenient ? new CustomElement(name) : new Element(name)));
}

private JSON processArrayElement(Element element, String defaultType)
{
JSONArray jsonArray = new JSONArray();
int childCount = element.getChildCount();
for(int i = 0; i < childCount; i++)
{
nu.xom.Node child = element.getChild(i);
if(child instanceof Text)
{
Text text = (Text)child;
if(StringUtils.isNotBlank(StringUtils.strip(text.getValue())))
jsonArray.element(text.getValue());
continue;
}
if(child instanceof Element)
setValue(jsonArray, (Element)child, defaultType);
}

return jsonArray;
}

private Object processElement(Element element, String type)
{
if(isNullObject(element))
return JSONNull.getInstance();
if(isArray(element, false))
return processArrayElement(element, type);
if(isObject(element, false))
return processObjectElement(element, type);
else
return trimSpaceFromValue(element.getValue());
}

private Element processJSONArray(JSONArray array, Element root, String expandableProperties[])
{
int l = array.size();
for(int i = 0; i < l; i++)
{
Object value = https://www.it610.com/article/array.get(i);
Element element = processJSONValue(value, root, null, expandableProperties);
root.appendChild(element);
}

return root;
}

private Element processJSONObject(JSONObject jsonObject, Element root, String expandableProperties[], boolean isRoot)
{
if(jsonObject.isNullObject())
{
root.addAttribute(new Attribute(addJsonPrefix("null"), "true"));
return root;
}
if(jsonObject.isEmpty())
return root;
if(isRoot && !rootNamespace.isEmpty())
{
setNamespaceLenient(true);
for(Iterator entries = rootNamespace.entrySet().iterator(); entries.hasNext(); )
{
java.util.Map.Entry entry = (java.util.Map.Entry)entries.next();
String prefix = (String)entry.getKey();
String uri = (String)entry.getValue();
if(StringUtils.isBlank(prefix))
root.setNamespaceURI(uri);
else
root.addNamespaceDeclaration(prefix, uri);
}

}
addNameSpaceToElement(root);
Object names[] = jsonObject.names().toArray();
Arrays.sort(names);
Element element = null;
label0:
for(int i = 0; i < names.length; i++)
{
String name = (String)names[i];
Object value = https://www.it610.com/article/jsonObject.get(name);
if(name.startsWith("@xmlns"))
{
setNamespaceLenient(true);
int colon = name.indexOf(':');
if(colon == -1)
{
if(StringUtils.isBlank(root.getNamespaceURI()))
root.setNamespaceURI(String.valueOf(value));
continue;
}
String prefix = name.substring(colon + 1);
if(StringUtils.isBlank(root.getNamespaceURI(prefix)))
root.addNamespaceDeclaration(prefix, String.valueOf(value));
continue;
}
if(name.startsWith("@"))
{
root.addAttribute(new Attribute(name.substring(1), String.valueOf(value)));
continue;
}
if(name.equals("#text"))
{
if(value instanceof JSONArray)
root.appendChild(((JSONArray)value).join("", true));
else
root.appendChild(String.valueOf(value));
continue;
}
if((value instanceof JSONArray) && (((JSONArray)value).isExpandElements() || ArrayUtils.contains(expandableProperties, name)))
{
JSONArray array = (JSONArray)value;
int l = array.size();
int j = 0;
do
{
if(j >= l)
continue label0;
Object item = array.get(j);
element = newElement(name);
if(item instanceof JSONObject)
element = processJSONValue((JSONObject)item, root, element, expandableProperties);
else
if(item instanceof JSONArray)
element = processJSONValue((JSONArray)item, root, element, expandableProperties);
else
element = processJSONValue(item, root, element, expandableProperties);
addNameSpaceToElement(element);
root.appendChild(element);
j++;
} while(true);
}
element = newElement(name);
element = processJSONValue(value, root, element, expandableProperties);
addNameSpaceToElement(element);
root.appendChild(element);
}

return root;
}

private Element processJSONValue(Object value, Element root, Element target, String expandableProperties[])
{
if(target == null)
target = newElement(getElementName());
if(JSONUtils.isBoolean(value))
{
if(isTypeHintsEnabled())
target.addAttribute(new Attribute(addJsonPrefix("type"), "boolean"));
target.appendChild(value.toString());
} else
if(JSONUtils.isNumber(value))
{
// if(isTypeHintsEnabled())
//target.addAttribute(new Attribute(addJsonPrefix("type"), "number"));
target.appendChild(value.toString());
} else
if(JSONUtils.isFunction(value))
{
if(value instanceof String)
value = https://www.it610.com/article/JSONFunction.parse((String)value);
JSONFunction func = (JSONFunction)value;
if(isTypeHintsEnabled())
target.addAttribute(new Attribute(addJsonPrefix("type"), "function"));
String params = ArrayUtils.toString(func.getParams());
params = params.substring(1);
params = params.substring(0, params.length() - 1);
target.addAttribute(new Attribute(addJsonPrefix("params"), params));
target.appendChild(new Text(""));
} else
if(JSONUtils.isString(value))
{
//if(isTypeHintsEnabled())
//target.addAttribute(new Attribute(addJsonPrefix("type"), "string"));
target.appendChild(value.toString());
} else
if(value instanceof JSONArray)
{
if(isTypeHintsEnabled())
target.addAttribute(new Attribute(addJsonPrefix("class"), "array"));
target = processJSONArray((JSONArray)value, target, expandableProperties);
} else
if(value instanceof JSONObject)
{
if(isTypeHintsEnabled())
target.addAttribute(new Attribute(addJsonPrefix("class"), "object"));
target = processJSONObject((JSONObject)value, target, expandableProperties, false);
} else
if(JSONUtils.isNull(value))
{
if(isTypeHintsEnabled())
target.addAttribute(new Attribute(addJsonPrefix("class"), "object"));
target.addAttribute(new Attribute(addJsonPrefix("null"), "true"));
}
return target;
}

private JSON processObjectElement(Element element, String defaultType)
{
if(isNullObject(element))
return JSONNull.getInstance();
JSONObject jsonObject = new JSONObject();
if(!skipNamespaces)
{
for(int j = 0; j < element.getNamespaceDeclarationCount(); j++)
{
String prefix = element.getNamespacePrefix(j);
String uri = element.getNamespaceURI(prefix);
if(StringUtils.isBlank(uri))
continue;
if(!StringUtils.isBlank(prefix))
prefix = ":" + prefix;
setOrAccumulate(jsonObject, "@xmlns" + prefix, trimSpaceFromValue(uri));
}

}
int attrCount = element.getAttributeCount();
for(int i = 0; i < attrCount; i++)
{
Attribute attr = element.getAttribute(i);
String attrname = attr.getQualifiedName();
if(!isTypeHintsEnabled() || addJsonPrefix("class").compareToIgnoreCase(attrname) != 0 && addJsonPrefix("type").compareToIgnoreCase(attrname) != 0)
{
String attrvalue = https://www.it610.com/article/attr.getValue();
setOrAccumulate(jsonObject, "@" + removeNamespacePrefix(attrname), trimSpaceFromValue(attrvalue));
}
}

int childCount = element.getChildCount();
for(int i = 0; i < childCount; i++)
{
nu.xom.Node child = element.getChild(i);
if(child instanceof Text)
{
Text text = (Text)child;
if(StringUtils.isNotBlank(StringUtils.strip(text.getValue())))
setOrAccumulate(jsonObject, "#text", trimSpaceFromValue(text.getValue()));
continue;
}
if(child instanceof Element)
setValue(jsonObject, (Element)child, defaultType);
}

return jsonObject;
}

private String removeNamespacePrefix(String name)
{
if(isRemoveNamespacePrefixFromElements())
{
int colon = name.indexOf(':');
return colon == -1 ? name : name.substring(colon + 1);
} else
{
return name;
}
}

private void setOrAccumulate(JSONObject jsonObject, String key, Object value)
{
if(jsonObject.has(key))
{
jsonObject.accumulate(key, value);
Object val = jsonObject.get(key);
if(val instanceof JSONArray)
((JSONArray)val).setExpandElements(true);
} else
{
jsonObject.element(key, value);
}
}

private void setValue(JSONArray jsonArray, Element element, String defaultType)
{
String clazz = getClass(element);
String type = getType(element);
type = type != null ? type : defaultType;
if(hasNamespaces(element) && !skipNamespaces)
{
jsonArray.element(simplifyValue(null, processElement(element, type)));
return;
}
if(element.getAttributeCount() > 0)
if(isFunction(element))
{
Attribute paramsAttribute = element.getAttribute(addJsonPrefix("params"));
String params[] = null;
String text = element.getValue();
params = StringUtils.split(paramsAttribute.getValue(), ",");
jsonArray.element(new JSONFunction(params, text));
return;
} else
{
jsonArray.element(simplifyValue(null, processElement(element, type)));
return;
}
boolean classProcessed = false;
if(clazz != null)
if(clazz.compareToIgnoreCase("array") == 0)
{
jsonArray.element(processArrayElement(element, type));
classProcessed = true;
} else
if(clazz.compareToIgnoreCase("object") == 0)
{
jsonArray.element(simplifyValue(null, processObjectElement(element, type)));
classProcessed = true;
}
if(!classProcessed)
if(type.compareToIgnoreCase("boolean") == 0)
jsonArray.element(Boolean.valueOf(element.getValue()));
else
if(type.compareToIgnoreCase("number") == 0)
try
{
jsonArray.element(Integer.valueOf(element.getValue()));
}
catch(NumberFormatException e)
{
jsonArray.element(Double.valueOf(element.getValue()));
}
else
if(type.compareToIgnoreCase("integer") == 0)
jsonArray.element(Integer.valueOf(element.getValue()));
else
if(type.compareToIgnoreCase("float") == 0)
jsonArray.element(Double.valueOf(element.getValue()));
else
if(type.compareToIgnoreCase("function") == 0)
{
String params[] = null;
String text = element.getValue();
Attribute paramsAttribute = element.getAttribute(addJsonPrefix("params"));
if(paramsAttribute != null)
params = StringUtils.split(paramsAttribute.getValue(), ",");
jsonArray.element(new JSONFunction(params, text));
} else
if(type.compareToIgnoreCase("string") == 0)
{
Attribute paramsAttribute = element.getAttribute(addJsonPrefix("params"));
if(paramsAttribute != null)
{
String params[] = null;
String text = element.getValue();
params = StringUtils.split(paramsAttribute.getValue(), ",");
jsonArray.element(new JSONFunction(params, text));
} else
if(isArray(element, false))
jsonArray.element(processArrayElement(element, defaultType));
else
if(isObject(element, false))
jsonArray.element(simplifyValue(null, processObjectElement(element, defaultType)));
else
jsonArray.element(trimSpaceFromValue(element.getValue()));
}
}

private void setValue(JSONObject jsonObject, Element element, String defaultType)
{
String clazz = getClass(element);
String type = getType(element);
type = type != null ? type : defaultType;
String key = removeNamespacePrefix(element.getQualifiedName());
if(hasNamespaces(element) && !skipNamespaces)
{
setOrAccumulate(jsonObject, key, simplifyValue(jsonObject, processElement(element, type)));
return;
}
if(element.getAttributeCount() > 0 && isFunction(element))
{
Attribute paramsAttribute = element.getAttribute(addJsonPrefix("params"));
String text = element.getValue();
String params[] = StringUtils.split(paramsAttribute.getValue(), ",");
setOrAccumulate(jsonObject, key, new JSONFunction(params, text));
return;
}
boolean classProcessed = false;
if(clazz != null)
if(clazz.compareToIgnoreCase("array") == 0)
{
setOrAccumulate(jsonObject, key, processArrayElement(element, type));
classProcessed = true;
} else
if(clazz.compareToIgnoreCase("object") == 0)
{
setOrAccumulate(jsonObject, key, simplifyValue(jsonObject, processObjectElement(element, type)));
classProcessed = true;
}
if(!classProcessed)
if(type.compareToIgnoreCase("boolean") == 0)
setOrAccumulate(jsonObject, key, Boolean.valueOf(element.getValue()));
else
if(type.compareToIgnoreCase("number") == 0)
try
{
setOrAccumulate(jsonObject, key, Integer.valueOf(element.getValue()));
}
catch(NumberFormatException e)
{
setOrAccumulate(jsonObject, key, Double.valueOf(element.getValue()));
}
else
if(type.compareToIgnoreCase("integer") == 0)
setOrAccumulate(jsonObject, key, Integer.valueOf(element.getValue()));
else
if(type.compareToIgnoreCase("float") == 0)
setOrAccumulate(jsonObject, key, Double.valueOf(element.getValue()));
else
if(type.compareToIgnoreCase("function") == 0)
{
String params[] = null;
String text = element.getValue();
Attribute paramsAttribute = element.getAttribute(addJsonPrefix("params"));
if(paramsAttribute != null)
params = StringUtils.split(paramsAttribute.getValue(), ",");
setOrAccumulate(jsonObject, key, new JSONFunction(params, text));
} else
if(type.compareToIgnoreCase("string") == 0)
{
Attribute paramsAttribute = element.getAttribute(addJsonPrefix("params"));
if(paramsAttribute != null)
{
String params[] = null;
String text = element.getValue();
params = StringUtils.split(paramsAttribute.getValue(), ",");
setOrAccumulate(jsonObject, key, new JSONFunction(params, text));
} else
if(isArray(element, false))
setOrAccumulate(jsonObject, key, processArrayElement(element, defaultType));
else
if(isObject(element, false))
setOrAccumulate(jsonObject, key, simplifyValue(jsonObject, processObjectElement(element, defaultType)));
else
setOrAccumulate(jsonObject, key, trimSpaceFromValue(element.getValue()));
}
}

private Object simplifyValue(JSONObject parent, Object json)
{
if(json instanceof JSONObject)
{
JSONObject object = (JSONObject)json;
if(parent != null)
{
Iterator entries = parent.entrySet().iterator();
do
{
if(!entries.hasNext())
break;
java.util.Map.Entry entry = (java.util.Map.Entry)entries.next();
String key = (String)entry.getKey();
Object value = https://www.it610.com/article/entry.getValue();
if(key.startsWith("@xmlns") && value.equals(object.opt(key)))
object.remove(key);
} while(true);
}
if(object.size() == 1 && object.has("#text"))
return object.get("#text");
}
return json;
}

private String trimSpaceFromValue(String value)
{
if(isTrimSpaces())
return value.trim();
else
return value;
}

private String writeDocument(Document doc, String encoding)
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try
{
XomSerializer serializer = encoding != null ? new XomSerializer(baos, encoding) : new XomSerializer(baos);
serializer.write(doc);
encoding = serializer.getEncoding();
}
catch(IOException ioe)
{
throw new JSONException(ioe);
}
String str = null;
try
{
str = baos.toString(encoding);
}
catch(UnsupportedEncodingException uee)
{
throw new JSONException(uee);
}
return str;
}

static Class _mthclass$(String x0) throws ClassNotFoundException
{
return Class.forName(x0);
}

private static final String EMPTY_ARRAY[] = new String[0];
private static final String JSON_PREFIX = "json_";
private static final Log log;
private String arrayName;
private String elementName;
private String expandableProperties[];
private boolean forceTopLevelObject;
private boolean namespaceLenient;
private Map namespacesPerElement;
private String objectName;
private boolean removeNamespacePrefixFromElements;
private String rootName;
private Map rootNamespace;
private boolean skipNamespaces;
private boolean skipWhitespace;
private boolean trimSpaces;
private boolean typeHintsCompatibility;
private boolean typeHintsEnabled;

static
{
log = LogFactory.getLog(net.sf.json.xml.Map2XML.class);
}
}


/*
DECOMPILATION REPORT

Decompiled from: D:\maven3.0.4\net\sf\json-lib\json-lib\2.4\json-lib-2.4-jdk15.jar
Total time: 472 ms
Jad reported messages/errors:
Couldn't resolve all exception handlers in method read
Couldn't fully decompile method readFromFile
Couldn't resolve all exception handlers in method readFromFile
Couldn't fully decompile method readFromStream
Couldn't resolve all exception handlers in method readFromStream
Couldn't fully decompile method _mthclass$
Couldn't resolve all exception handlers in method _mthclass$
Exit status: 0
Caught exceptions:
*/

    推荐阅读