有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java从资产中读取JSON文件

我试图使用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;

}

共 (1) 个答案

  1. # 1 楼答案

    试试这个:

    创建一个类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");
    

    其中级别。json是存储在asset文件夹中的json文件