在 Android 中读取 json 文件

我有以下 json 文件。我想知道我应该在我的项目中放置 json 文件,以及如何读取和存储它。

{
"aakash": [
[  0.070020,0.400684],
[  0.134198,0.515837],
[  0.393489,0.731809],
[  0.281616,0.739490]


],
"anuj": [
[  1287.836667,-22.104523],
[  -22.104523,308.689613],
[  775.712801,-13.047385],
[  -13.047385,200.067743]
]
}
142852 次浏览

Put that file in assets.

For project created in Android Studio project you need to create assets folder under the main folder.

Read that file as:

public String loadJSONFromAsset(Context context) {
String json = null;
try {
InputStream is = context.getAssets().open("file_name.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;


}

and then you can simply read this string return by this function as

JSONObject obj = new JSONObject(json_return_by_the_function);

For further details regarding JSON see http://www.vogella.com/articles/AndroidJSON/article.html

Hope you will get what you want.