本文介绍了org.json.JSONException:JSONArray文本必须以"["开头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下json文件:
I have the following json file:
[ { "1" : "b1.png"},
{ "2" : "bb1.png"},
{ "3" : "bbg1.png"}
]
以及以下行:
JSONArray array = new JSONArray(jsonFilePath);
我收到以下异常:
org.json.JSONException: A JSONArray text must start with '[' at 1 [character 2 line 1]
at org.json.JSONTokener.syntaxError(JSONTokener.java:433)
at org.json.JSONArray.<init>(JSONArray.java:105)
at org.json.JSONArray.<init>(JSONArray.java:144)
at il.ac.technion.cs234311.dolphins.parse.ParseCardsTest.initialize(ParseCardsTest.java:23)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
但是它以'['!!!
But it is start with '[' !!!
有什么想法吗?非常感谢!
Any ideas?Thanks a lot!
推荐答案
按照@JaredRummler的建议,您需要先将文件的内容读取到String中,然后将该String传递给JSONArray构造函数.这是一些使用 Apache Commons IO 来读取文件的示例代码:
As @JaredRummler suggested, you need to read the contents of the file into a String first, and then pass that String to the JSONArray constructor. Here's some sample code that uses Apache Commons IO to read the file:
import org.apache.commons.io.IOUtils;
...
public static String readJsonFile(String filename) throws IOException {
try (InputStream is = new FileInputStream(filename)) {
return IOUtils.toString(is, StandardCharsets.UTF_8);
}
}
....
JSONArray array = new JSONArray(readJsonFile(jsonFilePath));
这篇关于org.json.JSONException:JSONArray文本必须以"["开头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!