问题描述
我从文件获得了JSON字符串,如下所示:
I get a JSON string from a File like this:
我想像这样将其转换为JSONArray:
I'd like to convert it to a JSONArray like this:
Scanner scanner = new Scanner(file);
String json = scanner.useDelimiter("\\A").next();
JSONArray array = new JSONArray(json);`
但是,数组对象始终为空.怎么了?
However, the array object is always null. What is wrong here?
更新使用此代码时,可以在我的Android代码中正常工作:
UPDATEWorks correctly in my Android code when I use this:
Scanner scanner = new Scanner( context.getResources().openRawResource(R.raw.radar_search));
但是当我从文件创建以前的扫描仪时,它不起作用.一定有Android框架在正确执行某些操作,而Java却不是...
But it isn't working when I create my previous scanner from a File. There must be something that the Android framework is doing correctly that Java isn't...
更新2 我已经能够找出问题所在.当我使用Junit4对我的Android应用程序进行白盒测试时,就会发生这种情况.因此,我正在构造具有此帮助程序方法的新对象类,以创建JSONArray,并且在junit运行期间不会创建该对象类.不过,可以在常规的Java代码运行时中很好地创建它.
UPDATE 2I have been able to isolate the problem. It happens when I'm doing white-box testing of my Android application with Junit4. So, I am constructing this new object class which has this helper method to create a JSONArray, and it doesn't get created during the junit run. It gets created fine, though, in regular java code runtime.
推荐答案
我深入了解此问题,并找到了解决方案.事实证明,Android中的Junit测试无法访问Java JSON库.他们只能访问存根(默认情况下会抛出异常).因此,必须引入整个json库进行测试:
I got down to the bottom of this issue, and found a solution. It turns out that Junit tests in Android do not have access to the Java JSON library. They only have access to stubs (which throw exceptions by default). So one must pull in the entire json library for tests:
testCompile 'org.json:json:20160212'
您可以在Maven Central上找到json的最新版本号: http://mvnrepository.com /artifact/org.json/json
You can find the latest version number of json on maven central: http://mvnrepository.com/artifact/org.json/json
这篇关于无法从字符串创建Java JSONArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!