Android 앱 리소스에서 JSON 파일 사용
내 앱의 원시 리소스 폴더에 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();
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);
}
에서 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.
Like @mah states, the Android documentation (https://developer.android.com/guide/topics/resources/providing-resources.html) says that json files may be saved in the /raw directory under the /res (resources) directory in your project, for example:
MyProject/
src/
MyActivity.java
res/
drawable/
graphic.png
layout/
main.xml
info.xml
mipmap/
icon.png
values/
strings.xml
raw/
myjsonfile.json
Inside an Activity
, the json file can be accessed through the R
(Resources) class, and read to a String:
Context context = this;
Inputstream inputStream = context.getResources().openRawResource(R.raw.myjsonfile);
String jsonString = new Scanner(inputStream).useDelimiter("\\A").next();
This uses the Java class Scanner
, leading to less lines of code than some other methods of reading a simple text / json file. The delimiter pattern \A
means 'the beginning of the input'. .next()
reads the next token, which is the whole file in this case.
There are multiple ways to parse the resulting json string:
- Use the Java / Android built in JSONObject and JSONArray objects, like here: JSON Array iteration in Android/Java. It may be convenient to get Strings, Integers etc. using the
optString(String name)
,optInt(String name)
etc. methods, not thegetString(String name)
,getInt(String name)
methods, because theopt
methods return null instead of an exception in case of failing. - Use a Java / Android json serializing / deserializing library like the ones mentiod here: https://medium.com/@IlyaEremin/android-json-parsers-comparison-2017-8b5221721e31
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");
Using:
String json_string = readRawResource(R.raw.json)
Functions:
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() : "";
}
참고URL : https://stackoverflow.com/questions/6349759/using-json-file-in-android-app-resources
'program story' 카테고리의 다른 글
빌드 버전에 따라 앱 이름이 다르나요? (0) | 2020.10.13 |
---|---|
Windows 8 및 10에서 npm 경로 수정 (0) | 2020.10.13 |
android : 바이트를 dex로 변환하는 중 오류 발생 (0) | 2020.10.13 |
UILabel 텍스트의 픽셀 너비 (0) | 2020.10.13 |
Xcode 8에서 줄 삭제 키보드 단축키를 어떻게 만듭니 까? (0) | 2020.10.13 |