Using JSON File in Android App Resources

前端 未结 8 1198
盖世英雄少女心
盖世英雄少女心 2020-11-28 21:00

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?

8条回答
  •  鱼传尺愫
    2020-11-28 21:04

    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 constructUsingGson(Class 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);
       }
    

提交回复
热议问题