- 浏览: 725265 次
- 性别:
- 来自: 天津
文章分类
- 全部博客 (442)
- 中间件 (20)
- hibernate (13)
- spring (20)
- 数据库 (78)
- struts (8)
- ibatis (4)
- 前端 (61)
- linux,windows (21)
- it大环境 (32)
- IDE工具 (36)
- 感悟 (6)
- java基础 (40)
- 经典面试题 (10)
- exception总结 (14)
- 软件设计 (8)
- 工具类应用及新技术 (48)
- php (2)
- 微信 (1)
- 设计模式 (2)
- 重构 (3)
- 管理 (2)
- 工作笔记 (1)
- jmx (1)
- 算法 (4)
- 多线程同步 (2)
- 代码管理工具 (5)
- 代码检测及测试 (2)
- 缓存服务 (1)
- SOA及ROA (5)
- groovy (1)
- 网络编程 (2)
- 大数据 (6)
最新评论
-
love398146779:
我当然不能全写上面了,这只是其中一部分https连接。
java 建立 https连接 -
yuenkin:
大哥,这是双向认证吗?
java 建立 https连接 -
issu:
例如以下代码能遍历字符串"Tom:M ...
<c:forTokens>标签delims截取字符 -
love398146779:
2*3*5=30,是30个以上的请求才拒绝呀。
tomcat的maxThreads、acceptCount(最大线程数、最大排队数) -
love398146779:
2台跟1台一样的效果。
zookeeper与activemq最新存储replicatedLevelDB整合
1.这个转出来会有很多空格
2.此用法出来的很正规,因为我不用xml中写type类型,所以自已改了原代码
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<Object, Object> instance to xml string. Note: currently, * we aren't consider more about some collection types, such as array,list, * * @param dataMap the data map * * @return the string */ public static String converterPayPalm(Map<Object, Object> dataMap) { synchronized (MapToXMLString.class) { StringBuilder strBuilder = new StringBuilder(); strBuilder.append("<?xml version='1.0' encoding='UTF-8' ?>"); strBuilder.append("<paypalm>"); Set<Object> objSet = dataMap.keySet(); for (Object key : objSet) { if (key == null) { continue; } strBuilder.append("\n"); strBuilder.append("<").append(key.toString()).append(">\n"); Object value = dataMap.get(key); strBuilder.append(coverter(value).trim()); strBuilder.append("</").append(key.toString()).append(">\n"); } strBuilder.append("</paypalm>"); return strBuilder.toString(); } } /** * Converter Map<Object, Object> instance to xml string. Note: currently, * we aren't consider more about some collection types, such as array,list, * * @param dataMap the data map * * @return the string */ public static String converter(Map<Object, Object> dataMap, String xmlRootStart, String xmlRootEnd) { synchronized (MapToXMLString.class) { StringBuilder strBuilder = new StringBuilder(); strBuilder.append(xmlRootStart); Set<Object> objSet = dataMap.keySet(); for (Object key : objSet) { if (key == null) { continue; } strBuilder.append("\n"); strBuilder.append("<").append(key.toString()).append(">\n"); Object value = dataMap.get(key); strBuilder.append(coverter(value)); strBuilder.append("</").append(key.toString()).append(">\n"); } strBuilder.append(xmlRootEnd); return strBuilder.toString(); } } public static String coverter(Object[] objects) { StringBuilder strBuilder = new StringBuilder(); for(Object obj:objects) { strBuilder.append("<item className=").append(obj.getClass().getName()).append(">\n"); strBuilder.append(coverter(obj)); strBuilder.append("</item>\n"); } return strBuilder.toString(); } public static String coverter(Collection<?> objects) { StringBuilder strBuilder = new StringBuilder(); for(Object obj:objects) { strBuilder.append("<item className=").append(obj.getClass().getName()).append(">\n"); strBuilder.append(coverter(obj)); strBuilder.append("</item>\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<? extends Object> clz = object.getClass(); Field[] fields = clz.getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); if (field == null) { continue; } String fieldName = field.getName(); Object value = null; try { value = 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 == null) { strBuilder.append("null\n"); } else { strBuilder.append(value.toString() + "\n"); } strBuilder.append("</").append(fieldName).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 = 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 = text.getValue(); if(value.startsWith("<![CDATA[") && value.endsWith("]]>")) { value = value.substring(9); value = value.substring(0, value.length() - 3); writeRaw("<![CDATA["); 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 = 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 = 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 = 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("<![CDATA[" + func.getText() + "]]>")); } 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 = 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 = 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: */
发表评论
-
HttpUrlConnection与httpclient的速度
2015-03-10 17:59 886文件越大,可能HttpUrlConnection的速度优势越明 ... -
FastDFS与hadoop的HDFS区别
2015-01-12 16:12 4209主要是定位和应用场合不一样。 hadoop的文件系统HDFS主 ... -
RequestDispatcher实现文件下载
2015-01-04 14:55 754本来我使用的是文件流下载的方式,在Tomcat下可行,但是在W ... -
javax.mail.MessagingException: 501 5.0.0 HELO requires domain address
2014-12-22 17:32 7http://zouhuajian01.blog.163.co ... -
javax.mail.MessagingException: 501 5.0.0 HELO requires domain address
2014-12-22 17:32 1073http://zouhuajian01.blog.163.co ... -
https协议网页能够被搜索引擎收录吗?
2014-11-12 17:07 565百度现在只能收录少部分的https,大部分的https网页无法 ... -
aes加解密
2014-10-29 13:18 736import java.io.File; import ja ... -
udp测试
2014-10-22 15:39 505udp,常用于聊天室,直接向服务发送信息,不进行3次握手。 服 ... -
aio测试
2014-10-22 14:22 701由操作系统来做异步 服务端: package aio; ... -
fastdfs使用实战(Java实例篇)
2014-09-29 18:11 22532一、创建一个maven的webproject,叫file-ma ... -
谷歌(Chrome)安装Advanced REST Client插件
2014-09-29 10:44 2726以前用过jmeter测试各种url连接,soapui测试web ... -
sftp工具类
2014-09-28 13:29 958import java.io.File; import ja ... -
quartz配置
2014-09-22 10:35 380以前做过好几个quartz的应用项目,但都没有记录,当再次用到 ... -
ftp工具类
2014-09-19 18:08 741每回用到总去网上找一通,还是自已总结下比较好 package ... -
使用 JCaptcha 开发图形和声音验证码
2014-08-18 10:13 868http://www.ibm.com/developerwor ... -
Joda-Time 简介
2014-08-18 10:01 519iteye转的文章与自已的文章,不能放到一起。真麻烦。 转一个 ... -
log.isDebugEnabled()
2014-08-06 11:55 756在使用log4j,common-log这样的log框架时,发现 ... -
zookeeper与activemq最新存储replicatedLevelDB整合
2014-08-01 19:57 7026测试环境:三台VM虚拟机centos6.4 64位 mini版 ... -
一致性哈希算法原理 .
2014-08-01 19:53 554http://baike.baidu.com/view/158 ... -
json,xml互转
2014-06-20 19:00 606XMLSerializer xmlSerializer = n ...
相关推荐
将XML与Map进行互转是常见的需求,特别是在处理配置文件或者进行数据序列化时。本篇文章将详细介绍如何使用DOM4J库来实现XML和Map之间的转换,并讨论带有属性、无属性、有根节点和无根节点的情况。 DOM4J是一个强大...
1. **Java List转XML**: - 首先,我们需要一个包含多个Map对象的List。Map对象通常用于存储键值对,键和值可以是任何类型。 - 使用dom4j库,我们可以创建一个Document对象来表示XML文档,Element对象代表XML的...
这是一个很好用的工具栏,可以将xml字符串转换成map,或者将Map集合转换为xml字符串
xml与map转换 这个应用的情况并不多见,一般都在两个系统间沟通的时候会有xml和json的相互转换。因为map和json是天生可相互转换的,所以这里只有xml能和map进行转换,那json就不是问题了。
xml2map XML到MAP转换器的Golang编写的转换器 有时需要表示以前未知的结构。 这种通用表示形式通常是JSON,XML或数据映射结构形式的字符串。 类似于map [string] interface {}或map [interface {}] interface {}。 ...
本文将深入探讨如何使用Castor在Java和XML之间进行互转,并通过代码示例来阐述其工作原理。 ### 1. Castor简介 Castor是基于Java的,它通过生成Java类来解析XML文档,或者将Java对象转换为XML。它的核心功能包括:...
通过fastjson实现了JavaBean,list,MAP,list等格式与json格式之间的转换,已经附带fastjson的包,包的版本为fastjson-1.1.36.jar
```xml <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind <version>2.13.3 ``` 然后创建一个简单的JavaBean: ```java public class User { private String name; private int...
本文将深入探讨JSON和XML的特性,以及如何在Java中实现它们之间的互转。 JSON是一种轻量级的数据交换格式,它采用完全独立于语言的文本格式,但也使用了类似于C家族语言(包括Java)的习惯,使得人阅读和编写都相对...
要使用 `json-lib` 实现 JSON 与 Java 对象的互转,首先需要在项目中引入该库。如果你使用的是 Maven,可以在 `pom.xml` 文件中添加如下依赖: ```xml <groupId>net.sf.json-lib</groupId> <artifactId>json-lib...
本文将深入探讨`String`与JSON的互转方法,并提供一个简单的测试案例。 一、`String`转`JSON` 1. 使用`org.json`库 `org.json`库提供了一个名为`JSONObject`的类,可以将`String`转换为JSON对象。首先,确保你的...
在本项目中,`jackson-test`可能是一个包含测试代码的模块,用于演示如何使用Jackson进行JSON和Java对象的互转。 1. **安装Jackson库** 在Java项目中使用Jackson,通常需要将以下Maven依赖添加到`pom.xml`文件中:...
总之,Java和JSON之间的互转是常见的开发任务。`org.json`库提供了一系列的工具类,使这个过程变得简单易行。无论是将Java对象、Map还是List转换为JSON,或者反过来将JSON解析回Java对象,都有相应的API支持。了解并...
`json-lib`还提供了XML与JSON的互转功能,这对于需要在两者间切换的场景非常有用。 总结来说,`json-lib`是一个强大且易用的工具,它使得在Java中处理JSON变得简单。通过其提供的API,我们可以方便地进行JSON字符...
- **WMS(Web Map Service)**:一种Web服务标准,允许客户端请求和显示来自服务器的地图图像,通常使用XML来定义请求和响应格式。 #### 四、GIS领域的XML应用发展方向 随着技术的发展和需求的变化,GIS领域的XML...
Android MapAPI是Google提供的一种服务,它允许开发者在Android应用中集成交互式地图功能。MapAPI提供了丰富的功能,如地图显示、定位、路线规划、地理编码(地址转换为经纬度)和反地理编码(经纬度转换为地址)。...
DestinationObject destObject = mapper.map(sourceObject, DestinationObject.class); ``` 在上面的代码中,我们使用DozerBeanMapper类来将sourceObject对象转换为DestinationObject对象。 此外,我们还需要在...
此外,如果你需要将Java集合(如List或Map)转换为JSON,JSON-LIB也提供了相应的方法。例如,将一个List转换为JSON数组: ```java List<Person> people = new ArrayList(); people.add(person); JSONArray ...
4. **XML转换**:可以方便地将XML数据转换为其他数据结构,如List、Map等,反之亦然。 5. **XML构造**:使用Scala语法糖创建和修改XML文档,提高代码的可读性和简洁性。 6. **函数式解析和序列化**:Scalaz-XML提供...
总结来说,JSON-lib是Java开发者处理JSON数据的强大工具,它可以方便地进行Java对象与JSON之间的转换,以及JSON与XML之间的互操作,简化了数据交换和处理的复杂性。在实际项目中,根据需求选择合适的版本和配置,...