将静态JSON添加到Android Studio项目

Can*_*der 2 android json

我想将静态JSON添加到Android Studio项目中,然后可以在整个项目中引用它.有谁知道这样做的最佳方法?

更详细地说,我要做的是:1)从Google Places API中提取数据2)查找与静态JSON对象中的位置匹配的Google地方3)根据匹配项在地图上放置标记

我有数字1和3工作,但想知道在我的项目中创建静态(常量)JSON对象并将其用于第2步的最佳方法.

Igo*_*pov 7

您只需将JSON文件放入assets文件夹即可.稍后您将能够读取文件,解析它并使用值.


Can*_*der 7

上面发布的答案确实是我正在寻找的,但我想我会添加一些我实现的代码来帮助其他人进一步解决这个问题:

1)在assets文件夹中的txt文件中定义JSON对象

2)实现一种以字符串形式提取该对象的方法:

private String getJSONString(Context context)
{
    String str = "";
    try
    {
        AssetManager assetManager = context.getAssets();
        InputStream in = assetManager.open("json.txt");
        InputStreamReader isr = new InputStreamReader(in);
        char [] inputBuffer = new char[100];

        int charRead;
        while((charRead = isr.read(inputBuffer))>0)
        {
            String readString = String.copyValueOf(inputBuffer,0,charRead);
            str += readString;
        }
    }
    catch(IOException ioe)
    {
        ioe.printStackTrace();
    }

    return str;
}
Run Code Online (Sandbox Code Playgroud)

3)以您认为合适的任何方式解析对象.我的方法与此类似:

public void parseJSON(View view)
{
    JSONObject json = new JSONObject();

    try {
        json = new JSONObject(getJSONString(getApplicationContext()));
    } catch (JSONException e) {
        e.printStackTrace();
    }

   //implement logic with JSON here       
}
Run Code Online (Sandbox Code Playgroud)