I'm trying to parse a JSON file that looks like this:
[
{"character": "㐭", "definition": "blabla", "pinyin": ["lin"]},
// some more
{"character": "㐱", "definition": "blabla", "pinyin": ["zhen"]}
]
P.S. I don't have // some more
in json file
Which is situated in res/raw/dictionary.json folder. But I get the Exception Expected BEGIN_ARRAY but was STRING at line 1 column 1 path $
. I'm getting data like this:
InputStream is = getResources().openRawResource(R.id.dictionary);
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
int n;
while((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
finish(); // For now just finishing activity, gonna add handling later
} catch (IOException e) {
e.printStackTrace();
finish();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
finish();
}
}
String json = writer.toString();
JSONArray dictionary = new JSONArray(json);
// Do stuff with Array
First I thought error appeared because of the way I'm using to parse json, but when I commented out and then deleted all mechanism of parsing, it still showed me this error. Seems like it happens when android loads resources, but I'm not sure. I tried modifying json to following:
{
"characters": [
{"character": "㐭", "definition": "blabla", "pinyin": ["lin"]},
// some more
{"character": "㐱", "definition": "blabla", "pinyin": ["zhen"]}
]
}
And changing parsing mechanism
// Get resources
String json = writer.toString();
JSONObject dictionaryObj = new JSONObject(json);
JSONArray dictionary = dictionaryObj.getJSONArray("characters");
But that didn't help either. What can be wrong here?
N.B.: The problem is that I can't even test any solutions, because the activity is not loaded, the error appears during gradle build, in "run tasks" section