看看下面的代码片段。
键“sample”的值为字符串“[]”
put
和 accumulate
函数都将其转换为空数组 []
。
import net.sf.json.JSONObject;
public class sample {
public static void main(String[] args){
JSONObject resObj = new JSONObject();
resObj.put("sample","[]");
System.out.println(resObj);
}
}
输出:
{"sample":[]}
我想要原样的值(“[]”)。 像:
{"sample":"[]"}
如何解决这个问题?
更新:
上面的例子只是为了说明问题。
实际上,我正在从一个大的 XML 生成一个 JSON。 生成的 JSON 没有问题。
在将整个 JSON 字符串传递给累加和放置函数时面临此问题。
最佳答案
您使用的 json-lib
库是一个相当旧的实现,请尝试“官方”org.json 库,可以在 here 找到它。并使用maven
<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20170516</version>
</dependency>
然后
import org.json.JSONObject;
System.out.println( new JSONObject().put("sample","[]"));
将正确输出
{"sample":"[]"}
关于java - JSONObject 累加并把这个 "[]"字符串转换为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46405801/