-1

I have JSON file in assets and I'm trying to read it in my MainActivity method:

 private static List<JSONObject> getJSONArray(Context context) {
    JSONArray myJSONarr=new JSONArray();
    try
    {
        AssetManager am = context.getAssets();
        InputStream is = am.open("chineesecardsdata.json");
        String resultJson = is.toString();
        is.close();
        Log.d("mainActLog","file read ok: "+resultJson);

        try {
        }
        catch (JSONException e)
        {
        }
    }
    catch(
            IOException e)
    {
        Log.d("mainActLog","file read fail");
    }
}

In log I have:

file read ok: android.content.res.AssetManager$AssetInputStream@b123fb4

Olga
  • 159
  • 1
  • 3
  • 15

1 Answers1

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

parse JSON

try {
        JSONObject obj = new JSONObject(loadJSONFromAsset());
        JSONArray array = new JSONArray(loadJSONFromAsset());

        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
Naveen Tamrakar
  • 3,349
  • 1
  • 19
  • 28