我想在androidstudio中读取/解析json文件。
包含在assets文件夹中的json文件如下:
{
"Person":
{
"Name": "John"
}
}
应该读取文件的类是:
import ...
public class ParseJ
{
private Context context;
String name;
public String RetName() throws JSONException {
JSONObject obj = new JSONObject(loadJSONFromAsset());
JSONObject student = obj.getJSONObject("Person");
name = student.getString("Name");
return name;
}
public String loadJSONFromAsset()
{
String json = null;
try
{
InputStream is = context.getAssets().open("Test.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer,"UTF-8");
}
catch (IOException ex)
{
ex.printStackTrace();
return null;
}
return json;
}
}
然后在mainactivity中调用它,如下所示:
String firstname = new String();
ParseJ parsetest = new ParseJ();
TextView onomaTView;
try {
firstname = parsetest.RetName();
} catch (JSONException e) {
e.printStackTrace();
}
//textview
onomaTView = (TextView) findViewById(R.id.onoma);
onomaTView.setText("ONOMA:" + firstname);
}
当我构建并运行应用程序时,它会立即崩溃,并查看logcat,它会显示以下消息:原因:java.lang.nullpointerexception:尝试在空对象引用上调用虚拟方法“android.content.res.assetmanager android.content.context.getassets()”
这让我相信它不能读取文件,它只返回null。
1条答案
按热度按时间qyuhtwio1#
您得到的是空指针,因为上下文是空的,现在创建一个构造函数并像这样在其中传递上下文
然后在mainactivity中创建parsej的对象