我很难读取存储在资产文件夹中的本地json文件。
这是我编写的从文件读取并将对象添加到birdList ArrayList的方法。
我要去哪里错了?
public void getJSON() {
String jsonString;
try {
InputStream inputStream = getAssets().open("birds.json");
int size = inputStream.available();
byte[] buffer = new byte[size];
inputStream.read(buffer);
inputStream.close();
jsonString = new String(buffer, "UTF-8");
JSONArray jsonArray = new JSONArray(jsonString);
Log.e("MainActivity", "The json is: " + jsonString);
for(int i = 0; i < jsonArray.length();i++){
JSONObject obj = jsonArray.getJSONObject(i);
Bird bird = new Bird();
bird.setScientificName(obj.getString("scientific_name"));
bird.setCommonName(obj.getString("common_name"));
bird.setNumberImage(obj.getString("image"));
bird.setDescription(obj.getString("description"));
birdList.add(bird);
}
} catch (Exception e) {
e.printStackTrace();
}
}
这是我正在读取的json文件。
{
"birds": [
{
"scientific_name": "Cyanocitta stelleri",
"common_name": "Steller's jay",
"image": "stellers_jay",
"description": "The Steller's jay is a jay native to western North America, closely related to the blue jay found in the rest of the continent, but with a black head and upper body. It is also known as the long-crested jay, mountain jay, Braham's jay and pine jay. It is the only crested jay west of the Rocky Mountains."
},
{
"scientific_name": "Tachycineta thalassina",
"common_name": "Violet-green swallow",
"image": "violet_green_swallow",
"description": "The violet-green swallow is a small North American passerine bird in the swallow family. These aerial insectivores are distributed along the west coast from Alaska to Mexico, extending as far east as Montana and Texas. With an appearance very similar to the tree swallow, these individuals can be identified by the white rump side-patches that appear to separate their green back and purple tail. "
},
{
"scientific_name": "Turdus migratorius",
"common_name": "American robin",
"image": "american_robin",
"description": "The American robin is a migratory songbird of the true thrush genus and Turdidae, the wider thrush family. It is named after the European robin[2] because of its reddish-orange breast, though the two species are not closely related, with the European robin belonging to the Old World flycatcher family. The American robin is widely distributed throughout North America, wintering from southern Canada to central Mexico and along the Pacific Coast. "
}
]
}
任何帮助将不胜感激
JSONArray jsonArray = new JSONArray(jsonString);
修改成 String data = jsonString.getString("birds"); JSONArray jsonArray = JSONArray.fromObject(data);
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。