java - java中的xml到json转换问题,第一个前导零从字符串中丢弃

标签 java xml json

我的 xml 包含属性值“0123”,我想将其视为字符串, 按照以下代码从 xml 转换为 json 后 属性值中的前导零被丢弃。

使用的类

import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.json.JSONObject;
import org.json.XML;

//将xml转换为json

    org.jdom.Document jdomDocument = new Document();
    org.jdom.Element Attribute = new org.jdom.Element("Attribute");
    jdomDocument.setRootElement(Attribute);

    org.jdom.Element valueElement = new  org.jdom.Element("Value");
    valueElement.setText(getValue()); // "0123"
   // getValue() return anything like boolean,string,long,date, time etc..

     root.addContent(valueElement);
    String xmlval = new    XMLOutputter(Format.getPrettyFormat()).outputString(jdomDocument);
    JSONObject xmlJSONObj = XML.toJSONObject(xmlval);
    String jsonPrettyPrintString = xmlJSONObj.toString(4);

如何解决这个问题?

最佳答案

查看code for XML.java - 特别是 stringToValue 方法,它执行

"Try to convert a string into a number, boolean, or null".  

代码如下 - 您可以看到它首先尝试解析为数字,在这种情况下它将修剪前导零。为了测试你可以尝试在你的字符串中添加一个非数字字符 - 我认为它会保留前导零。

看起来您所看到的行为已融入到库中。 这不太好,尽管函数 toJSONObject 的文档确实发出了警告

"Some information may be lost in this transformation because JSON is a data format and XML is a document format"

代码:

// If it might be a number, try converting it. If that doesn't work,
// return the string.

        try {
            char initial = string.charAt(0);
            boolean negative = false;
            if (initial == '-') {
                initial = string.charAt(1);
                negative = true;
            }
            if (initial == '0' && string.charAt(negative ? 2 : 1) == '0') {
                return string;
            }
            if ((initial >= '0' && initial <= '9')) {
                if (string.indexOf('.') >= 0) {
                    return Double.valueOf(string);
                } else if (string.indexOf('e') < 0 && string.indexOf('E') < 0) {
                    Long myLong = new Long(string);
                    if (myLong.longValue() == myLong.intValue()) {
                        return new Integer(myLong.intValue());
                    } else {
                        return myLong;
                    }
                }
            }
        } catch (Exception ignore) {
        }

编辑: 这看起来像是库中的一个错误。我相信它应该使用

(negative ? 1 : 0)

因为当前行为错误地将带有单个前导零的值解释为数字。正如提问者所确认的,它正确地将两个或多个前导零识别为字符串。

关于java - java中的xml到json转换问题,第一个前导零从字符串中丢弃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18121714/

相关文章:

xml - 在go中遍历xml

.net - 如何实现简单的XPath查找

jquery - Jstree 在加载时打开特定分支

javascript - 如何将时间戳添加到 package.json 中的脚本中?

java - 我在哪里可以学习 Java GUI 创建

java - org.hibernate.AnnotationException : mappedBy reference an unknown target entity property. 有错误 : java. lang.NullPointerException

java - 无法在 Swing Explorer 中加载主类

java - 尝试在 EditText 中将数字设置为文本

javascript - 将数组传递给函数,如何?

java - 如何创建 ear 文件,并在其中包含 war 和 jar 文件