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

5t7ly7z5  于 2023-01-06  发布在  Android
关注(0)|答案(8)|浏览(123)

假设我在应用的raw resources文件夹中有一个包含JSON内容的文件,如何将其读入应用,以便解析JSON?

fxnxkyjh

fxnxkyjh1#

请参见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();
xbp102n0

xbp102n02#

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

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

qkf9rpyu3#

我使用@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);
   }
g52tjvyc

g52tjvyc4#

与@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(资源)类访问json文件,并将其读取为String:

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

这使用了Java类Scanner,与其他阅读简单文本/ json文件的方法相比,使用了更少的代码行。分隔符模式\A表示“输入的开始”。.next()读取下一个标记,在本例中是整个文件。
有多种方法可以解析生成的JSON字符串:

qjp7pelc

qjp7pelc5#

http://developer.android.com/guide/topics/resources/providing-resources.html开始:

    • 原始/**

要以原始格式保存的任意文件。要使用原始InputStream打开这些资源,请使用资源ID(即R.raw.filename)调用Resources. openRawResource()。
但是,如果您需要访问原始文件名和文件层次结构,您可以考虑将一些资源保存在assets/目录(而不是res/raw/)中。assets/中的文件没有资源ID,因此您只能使用AssetManager读取它们。

m0rkklqb

m0rkklqb6#

找到了this Kotlin snippet answer very helpful
虽然最初的问题是获取JSON字符串,但我想有些人可能会觉得这很有用。进一步使用Gson会得到这个具有具体化类型的小函数:

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

请注意,您希望使用TypeToken,而不仅仅是T::class,因此如果您读取List<YourType>,您不会逐个类型地丢失擦除。
通过类型推断,你可以像这样使用:

fun pricingData(): List<PricingData> = readRawJson(R.raw.mock_pricing_data)
5vf7fwbs

5vf7fwbs7#

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");
watbbzwu

watbbzwu8#

使用:

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() : "";
}

相关问题