Cannot create a Java JSONArray from String

久未见 提交于 2019-12-12 02:56:34

问题


I get a JSON string from a File like this:

"[ { "id": "eVgoHOU0000000011", "network": { "networkName": "EVgo" }, "status": "Available", "plugscore": 9, "stationname": "Wholefoods Market", "description": "Very dependable station next to store.", "location": { "latitude": 30.596481, "longitude": -96.353554, "address": { "address1": "Golden Acres", "address2": "second floor", "city": "College Station", "state": "TX", "zipcode": "77029" }, "description": "Map marker location is next to gas station." }, "connectors": [ { "type": "US Wall Outlet", "power": "40 amp", "status": "Uknown" }, { "type": "US Wall Outlet", "power": "40 amp", "status": "Uknown" }, { "type": "CHAdeMO", "power": "40 amp", "status": "Unavailable" } ], "planName": "No Charge to Charge" }]"

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?

UPDATE Works correctly in my Android code when I use this:

Scanner scanner = new Scanner( context.getResources().openRawResource(R.raw.radar_search));

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...

UPDATE 2 I 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.


回答1:


If the file includes the outer double-quotes, then new JSONArray(...) will throw JSONException. If it does not, I see no problem here.

Technically a Java constructor cannot return null. Use a debugger to step through the code. You could be ignoring an uncaught exception.




回答2:


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'

You can find the latest version number of json on maven central: http://mvnrepository.com/artifact/org.json/json



来源:https://stackoverflow.com/questions/36187190/cannot-create-a-java-jsonarray-from-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!