简体   繁体   English

从资产读取JSON文件

[英]Read JSON file from assets

I am trying to read a JSON file from assets in fragment using getAssets() , but the IDE says "can not resolve this method (getAssets())". 我正在尝试使用getAssets()从片段中的资产读取JSON文件,但是IDE表示“无法解析此方法(getAssets())”。

Code

 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;

}

Try this: 尝试这个:

Create a class LoaderHelper.java 创建一个类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;
    }
}

To get the json string call the above class as: 要获取json字符串,请按以下方式调用上述类:

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

where levels.json is the json file stored in asset folder. 其中levels.json是存储在asset文件夹中的json文件。

Method getAssets() is part of Context class. 方法getAssets()是Context类的一部分。 So if you're not calling loadJSONFromAsset() in the class that extends Context, eg Activity, you need to provide reference to Context as an argument to your method and then call getAssets() on it 因此,如果您不在扩展Context的类中调用loadJSONFromAsset()例如Activity),则需要提供对Context的引用作为方法的参数,然后在其上调用getAssets()

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

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