Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JSON File in Android App Resources

Tags:

json

android

Suppose I have a file with JSON contents in the raw resources folder in my app. How can I read this into the app, so that I can parse the JSON?

like image 345
yydl Avatar asked Jun 14 '11 20:06

yydl


People also ask

Can JSON be used in mobile application?

These formats can be XML file format or JSON file format. When you want to use the data store using these file formats in the database, then you have to apply some kind of parsing of data in your Android Application. For JSON file you have to use the JSON parsing and for XML files, you can use the XML parsing.

Where do I put JSON files on Android?

json file is generally placed in the app/ directory (at the root of the Android Studio app module).

How does JSON handle data in Android?

JSON stands for JavaScript Object Notation.It is an independent data exchange format and is the best alternative for XML. This chapter explains how to parse the JSON file and extract necessary information from it. Android provides four different classes to manipulate JSON data.


3 Answers

See openRawResource. Something like this should work:

InputStream is = getResources().openRawResource(R.raw.json_file);
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
    Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
    int n;
    while ((n = reader.read(buffer)) != -1) {
        writer.write(buffer, 0, n);
    }
} finally {
    is.close();
}

String jsonString = writer.toString();
like image 93
kabuko Avatar answered Oct 19 '22 00:10

kabuko


Kotlin is now official language for Android, so I think this would be useful for someone

val text = resources.openRawResource(R.raw.your_text_file)
                                 .bufferedReader().use { it.readText() }
like image 138
Dima Rostopira Avatar answered Oct 18 '22 22:10

Dima Rostopira


I used @kabuko's answer to create an object that loads from a JSON file, using Gson, from the Resources:

package com.jingit.mobile.testsupport;

import java.io.*;

import android.content.res.Resources;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;


/**
 * An object for reading from a JSON resource file and constructing an object from that resource file using Gson.
 */
public class JSONResourceReader {

    // === [ Private Data Members ] ============================================

    // Our JSON, in string form.
    private String jsonString;
    private static final String LOGTAG = JSONResourceReader.class.getSimpleName();

    // === [ Public API ] ======================================================

    /**
     * Read from a resources file and create a {@link JSONResourceReader} object that will allow the creation of other
     * objects from this resource.
     *
     * @param resources An application {@link Resources} object.
     * @param id The id for the resource to load, typically held in the raw/ folder.
     */
    public JSONResourceReader(Resources resources, int id) {
        InputStream resourceReader = resources.openRawResource(id);
        Writer writer = new StringWriter();
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(resourceReader, "UTF-8"));
            String line = reader.readLine();
            while (line != null) {
                writer.write(line);
                line = reader.readLine();
            }
        } catch (Exception e) {
            Log.e(LOGTAG, "Unhandled exception while using JSONResourceReader", e);
        } finally {
            try {
                resourceReader.close();
            } catch (Exception e) {
                Log.e(LOGTAG, "Unhandled exception while using JSONResourceReader", e);
            }
        }

        jsonString = writer.toString();
    }

    /**
     * Build an object from the specified JSON resource using Gson.
     *
     * @param type The type of the object to build.
     *
     * @return An object of type T, with member fields populated using Gson.
     */
    public <T> T constructUsingGson(Class<T> type) {
        Gson gson = new GsonBuilder().create();
        return gson.fromJson(jsonString, type);
    }
}

To use it, you'd do something like the following (the example is in an InstrumentationTestCase):

   @Override
    public void setUp() {
        // Load our JSON file.
        JSONResourceReader reader = new JSONResourceReader(getInstrumentation().getContext().getResources(), R.raw.jsonfile);
        MyJsonObject jsonObj = reader.constructUsingGson(MyJsonObject.class);
   }
like image 26
jwir3 Avatar answered Oct 18 '22 23:10

jwir3