How to get a json file from raw folder?

11,115

Solution 1

ObjectMapper.readValue also take InputStream as source . Get InputStream using openRawResource method from json file and pass it to readValue :

InputStream in = getResources().openRawResource(R.raw.user);
User user = mapper.readValue(in, User.class);

Solution 2

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();

Solution 3

Kotlin way :

val raw = resources.openRawResource(R.raw.posts)
        val writer: Writer = StringWriter()
        val buffer = CharArray(1024)
        raw.use { rawData ->
            val reader: Reader = BufferedReader(InputStreamReader(rawData, "UTF-8"))
            var n: Int
            while (reader.read(buffer).also { n = it } != -1) {
                writer.write(buffer, 0, n)
            }
        }

        val jsonString = writer.toString()
Share:
11,115
machichiotte
Author by

machichiotte

...

Updated on June 04, 2022

Comments

  • machichiotte
    machichiotte almost 2 years

    I want to use my user.json which is in my raw folder to get a new File :

    // read from file, convert it to user class
    User user = mapper.readValue(new File(**R.raw.user**), User.class);
    

    I found that InputStream can do it :

    InputStream ins = res.openRawResource(
                            getResources().getIdentifier("raw/user",
                                    "raw", getPackageName()));
    

    Is there a better way to do it, directly with my json file ID ?

  • Blackbelt
    Blackbelt over 8 years
    assets and raw are different folders, aren't they ?