Jason Macville
Jason Macville

Reputation: 93

"FileNotFoundException" when trying to read from JSON file in Android Studio

I'm trying to construct a list with objects from a JSON file in Android Studio. The JSON file "compliments.json" is placed in the map app/src/main/res.

I keep getting an "java.io.FileNotFoundException" when I tried to read in this file. I've tried a lot of solutions that people in similar threads suggested. (I cleared the cache, I changed the file to another map and I tried a new way of reading), but none of them seem to work. Here is the code that I use to read in the file:

public static ComplimentCatalog read(Context context) throws JSONException, IOException {
        ComplimentCatalog ul = new ComplimentCatalog();

        JsonParser parser = new JsonParser();

        AssetManager assetManager = context.getAssets();
        InputStream ims = assetManager.open("compliments.json");
        Reader reader1 = new InputStreamReader(ims);

        JsonElement rootElement = parser.parse(reader1);
        JsonObject rootObject = rootElement.getAsJsonObject();
        JsonArray uList = rootObject.getAsJsonArray("complimentList");

        for(int i = 0; i < uList.size(); i++) {
            JsonObject jsnComp = uList.get(i).getAsJsonObject();
            ul.add(Compliment.read(jsnComp));
        }
        System.out.println("UL:" + ul.toString());
        return ul;
    }

And here is the json:

    {
  "complimentList":[
    {
      "text": "You look good today!"
    },
    {
      "text": "Do you have a new T-Shirt?"
    }
  ]
}

If you need any other files/information, I would be glad to provide them.

Upvotes: 0

Views: 1760

Answers (2)

AnasAbubacker
AnasAbubacker

Reputation: 3607

You should create a new folder named assets and place compliments.json in that folder.

AssetManager will look for files inside assets folder.

enter image description here

Upvotes: 0

Yohannes Gebremariam
Yohannes Gebremariam

Reputation: 2265

If you are going to use AssetManager assetManager = context.getAssets(); Your file should be placed in app/src/main/assets/.

Upvotes: 1

Related Questions