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

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

如果我要将字符串放入android的String资源中,并通过getResources()。getString(R.String.name)动态使用它怎么办?

对我来说,由于引号而无法使用,引号在阅读时会被忽略,而且似乎也无法转义

有什么方法可以使ButterKnife绑定原始资源?仅仅为了读取一个字符串而编写10行以上的代码似乎有点过大了。

json如何存储在资源中?只是在es\json_file.json文件夹内还是在es

aw\json_file.json内?

该答案缺少关键信息。 getResources()在哪里可以调用?原始资源文件应该放在哪里?您应遵循哪些约定以确保构建工具创建R.raw.json_file?

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

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

我使用@kabuko的答案来创建一个对象,该对象使用Gson从资源中的JSON文件中加载:

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

实现这一目标的方法非常不错。谢谢!

不要忘记将依赖项{compile com.google.code.gson:gson:2.8.2}添加到gradle文件中

GSON的最新版本是implementation com.google.code.gson:gson:2.8.5

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

raw/

Arbitrary files to save in their raw form. To open these resources with a raw InputStream, call Resources.openRawResource() with the resource ID, which is R.raw.filename.

However, if you need access to original file names and file hierarchy, you might consider saving some resources in the assets/ directory (instead of res/raw/). Files in assets/ are not given a resource ID, so you can read them only using AssetManager.

如果我想在应用程序中嵌入JSON文件,应该放在哪里?在资产文件夹还是原始文件夹中?谢谢!

就像@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

在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,与其他一些读取简单text / json文件的方法相比,所需的代码行更少。分隔符模式\A表示"输入的开始"。 .next()读取下一个标记,在这种情况下,它是整个文件。

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

使用内置于JSONObject和JSONArray对象中的Java / Android,如下所示:Android / Java中的JSON Array迭代。使用optString(String name),optInt(String name)等方法而不是getString(String name),getInt(String name)方法来获取Strings,Integers等可能很方便,因为opt方法返回null而不是异常。失败。

使用Java / Android json序列化/反序列化库,就像这里提到的那样:https://medium.com/@IlyaEremin/android-json-parsers-comparison-2017-8b5221721e31

这应该是公认的答案,只需两行就可以完成。

需要import java.util.Scanner; import java.io.InputStream; import android.content.Context;

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

使用方法:

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