小编典典

在Android中读取json文件

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]
]
}

阅读 428

收藏
2020-07-27

共1个答案

小编典典

将该文件放入资产中

对于在Android Studio项目中创建的项目,您需要在主文件夹下创建资产文件夹。

将该文件读取为:

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;

    }

然后您可以简单地string通过此函数读取此返回

JSONObject obj = new JSONObject(json_return_by_the_function);

有关JSON的更多详细信息,请参见
http://www.vogella.com/articles/AndroidJSON/article.html

希望你能得到想要的。

2020-07-27