gpt4 book ai didi

java - 使用 org.json 从 XML 转换为 JSON : how to preserve number format?

转载 作者:行者123 更新时间:2023-12-01 19:28:31 24 4
gpt4 key购买 nike

我正在使用 org.json lib 将简单的 XML 转换为 JSON:

import org.json.JSONObject;
import org.json.XML;

public class TestJson {
public static void test_number() {
String xml = "<BALANCE>32032033.10</BALANCE>";
JSONObject jsonObj = XML.toJSONObject(xml);
String json_str = jsonObj.toString(4);
System.out.println(String.format("%s\n----\n%s", xml, json_str));
}

public static void main(String[] args) {
try {
test_number();
} catch (Exception e) {
e.printStackTrace();
}
}
}

我的结果:

<BALANCE>32032033.10</BALANCE>
----
{"BALANCE": 3.20320331E7}

如您所见,数字格式从普通格式更改为科学格式。如何保留数字格式?我希望将 JSON 视为:

{"BALANCE": 32032033.10}

或者最好作为字符串:

{"BALANCE": "32032033.10"}

我使用 json-20190722.jar 中的 org.json

最佳答案

希望下面的代码能够帮助解决这个问题。请使用 XML.toJSONObject(xml,true) 而不是 XML.toJSONObject(xml);

import org.json.JSONObject;
import org.json.XML;

public class TestJson {
public static void test_number() {
String xml = "<BALANCE>32032033.10</BALANCE>";
JSONObject jsonObj = XML.toJSONObject(xml,true);
System.out.println(String.format("%s\n----\n%s", xml, jsonObj.toString()));
}

public static void main(String[] args) {
try {
test_number();
} catch (Exception e) {
e.printStackTrace();
}
}
}

输出:

<BALANCE>32032033.10</BALANCE>
----
{"BALANCE":"32032033.10"}

关于java - 使用 org.json 从 XML 转换为 JSON : how to preserve number format?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60596651/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com