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

yyd*_*ydl 77 android json

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

kab*_*uko 133

请参阅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();
Run Code Online (Sandbox Code Playgroud)

  • 这个答案缺乏关键信息。在哪里可以调用 getResources() ?原始资源文件应该放在哪里?您应该遵循什么约定来确保构建工具创建“R.raw.json_file”? (2认同)

Dim*_*ira 88

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

val text = resources.openRawResource(R.raw.your_text_file)
                                 .bufferedReader().use { it.readText() }
Run Code Online (Sandbox Code Playgroud)

  • @AndrewOrobator 我怀疑有人会将大 json 放入应用程序资源中,但是是的,很好的一点 (3认同)

jwi*_*ir3 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

要使用它,您将执行以下操作(示例位于以下内容中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);
   }
Run Code Online (Sandbox Code Playgroud)

  • 不要忘记将依赖项{compile com.google.code.gson:gson:2.8.2'}添加到您的gradle文件中 (3认同)

mah*_*mah 12

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

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

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

  • 如果我想在我的应用程序中嵌入一个JSON文件,我应该把它放在哪里?在assets文件夹或原始文件夹中?谢谢! (3认同)

the*_*jon 9

发现这个 Kotlin 代码片段答案非常有帮助\xe2\x99\xa5\xef\xb8\x8f

\n

虽然最初的问题要求获取 JSON 字符串,但我认为有些人可能会发现这很有用。更进一步,可以Gson得到这个具有具体化类型的小函数:

\n
private inline fun <reified T> readRawJson(@RawRes rawResId: Int): T {\n    resources.openRawResource(rawResId).bufferedReader().use {\n        return gson.fromJson<T>(it, object: TypeToken<T>() {}.type)\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

请注意,您想要使用的TypeToken不仅仅是T::class这样,如果您阅读 aList<YourType>您不会丢失类型擦除。

\n

通过类型推断,您可以像这样使用:

\n
fun pricingData(): List<PricingData> = readRawJson(R.raw.mock_pricing_data)\n
Run Code Online (Sandbox Code Playgroud)\n


ʕ ᵔ*_*ᵔ ʔ 7

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

MyProject/
  src/ 
    MyActivity.java
  res/
    drawable/ 
        graphic.png
    layout/ 
        main.xml
        info.xml
    mipmap/ 
        icon.png
    values/ 
        strings.xml
    raw/
        myjsonfile.json
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

  • 使用内置于JSONObjectJSONArray对象中的Java / Android ,如下所示:Android / Java中的JSON Array迭代。这可能是方便使用来获得字符串,整数等等optString(String name)optInt(String name)等等方法,而不是getString(String name)getInt(String name)方法,因为opt方法失败的情况下返回null而不是一个异常的。
  • 使用Java / Android json序列化/反序列化库,就像这里提到的那样:https ://medium.com/@IlyaEremin/android-json-parsers-comparison-2017-8b5221721e31


Nic*_*hek 5

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");
Run Code Online (Sandbox Code Playgroud)


Mah*_*nei 5

使用:

String json_string = readRawResource(R.raw.json)
Run Code Online (Sandbox Code Playgroud)

功能:

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() : "";
}
Run Code Online (Sandbox Code Playgroud)