繁体   English   中英

从资产读取JSON文件

[英]Read JSON file from assets

我正在尝试使用getAssets()从片段中的资产读取JSON文件,但是IDE表示“无法解析此方法(getAssets())”。

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

}

尝试这个:

创建一个类LoaderHelper.java

public class LoaderHelper {
    public static String getJson(Context context, String json){
        String jsonString=parseFileToString(context, json);
        return jsonString;
    }
    public static String parseFileToString( Context context, String filename )
    {
        try
        {
            InputStream stream = context.getAssets().open( filename );
            int size = stream.available();

            byte[] bytes = new byte[size];
            stream.read(bytes);
            stream.close();

            return new String( bytes );

        } catch ( IOException e ) {
            Log.i("GuiFormData", "IOException: " + e.getMessage() );
        }
        return null;
    }
}

要获取json字符串,请按以下方式调用上述类:

String str=LoaderHelper.parseFileToString(context, "levels.json");

其中levels.json是存储在asset文件夹中的json文件。

方法getAssets()是Context类的一部分。 因此,如果您不在扩展Context的类中调用loadJSONFromAsset()例如Activity),则需要提供对Context的引用作为方法的参数,然后在其上调用getAssets()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM