在Android应用程序资源中使用JSON文件

问题描述 投票:72回答:7

假设我的应用程序的原始资源文件夹中有一个带有JSON内容的文件。如何将其读入应用程序,以便我可以解析JSON?

android json
7个回答
132
投票

openRawResource。这样的事情应该有效:

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

75
投票

Kotlin现在是Android的官方语言,所以我认为这对某人有用

val text = resources.openRawResource(R.raw.your_text_file)
                                 .bufferedReader().use { it.readText() }

22
投票

我使用@kabuko的答案来创建一个从JSON文件加载的对象,使用Gson,来自参考资料:

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

要使用它,您将执行以下操作(示例位于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);
   }

12
投票

来自http://developer.android.com/guide/topics/resources/providing-resources.html

生的/ 任意文件以原始形式保存。要使用原始InputStream打开这些资源,请使用资源ID(即R.raw.filename)调用Resources.openRawResource()。

但是,如果需要访问原始文件名和文件层次结构,可以考虑在assets /目录中保存一些资源(而不是res / raw /)。资产/中的文件未获得资源ID,因此您只能使用AssetManager读取它们。


7
投票

与@mah状态一样,Android文档(https://developer.android.com/guide/topics/resources/providing-resources.html)表示json文件可以保存在项目中/ res(resources)目录下的/ raw目录中,例如:

MyProject/
  src/ 
    MyActivity.java
  res/
    drawable/ 
        graphic.png
    layout/ 
        main.xml
        info.xml
    mipmap/ 
        icon.png
    values/ 
        strings.xml
    raw/
        myjsonfile.json

Activity中,可以通过R(Resources)类访问json文件,并读取到String:

Context context = this;
Inputstream inputStream = context.getResources().openRawResource(R.raw.myjsonfile);
String jsonString = new Scanner(inputStream).useDelimiter("\\A").next();

这使用Java类Scanner,导致比读取简单text / json文件的其他方法更少的代码行。分隔符模式\A表示“输入的开始”。 .next()读取下一个标记,在这种情况下是整个文件。

有多种方法可以解析生成的json字符串:


4
投票
InputStream is = mContext.getResources().openRawResource(R.raw.json_regions);
                            int size = is.available();
                            byte[] buffer = new byte[size];
                            is.read(buffer);
                            is.close();
                           String json = new String(buffer, "UTF-8");

0
投票

使用:

String json_string = readRawResource(R.raw.json)

功能:

public String readRawResource(@RawRes int res) {
    return readStream(context.getResources().openRawResource(res));
}

private String readStream(InputStream is) {
    Scanner s = new Scanner(is).useDelimiter("\\A");
    return s.hasNext() ? s.next() : "";
}
© www.soinside.com 2019 - 2024. All rights reserved.