내 애플리케이션의 원시 리소스 폴더에 JSON 콘텐츠가있는 파일이 있다고 가정 해 보겠습니다. 어떻게하면 JSON을 파싱 할 수 있을까요? http://developer.android.com/guide/topics/resources/providing-resources.html에서Android 애플리케이션 리소스에서 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();
:
원료/
임의의 파일은 원시 형태로 저장합니다. 원시 InputStream을 사용하여 이러한 리소스를 열려면 리소스 ID (R.raw.filename)로 Resources.openRawResource()를 호출합니다.그러나 원본 파일 이름 및 파일 계층에 대한 액세스가 필요한 경우 res/raw/대신 assets/디렉토리에 일부 리소스를 저장하는 것이 좋습니다. 애셋 내의 파일 /에는 리소스 ID가 주어지지 않으므로 AssetManager 만 사용하여 읽을 수 있습니다.
JSON 파일을 내 앱에 삽입하려는 경우 어디에 넣어야합니까? 자산 폴더 또는 원시 폴더에 있습니까? 감사! – Ricardo
나는 자원에서 JSON 파일에서로드, Gson를 사용하여 개체를 만들 @의 kabuko의 답변을 사용 :
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);
}
위대한 :)! 고맙습니다. – nikolaDev
이것을 달성하는 정말 좋은 좋은 재사용 방법. 감사! – speedynomads
당신의 gradle 파일에 의존성을 추가하는 것을 잊지 마세요. {comile.code.gson : gson : 2.8.2 '} – patrics
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");
Kotli n은 이제 Android 용 공식 언어이므로 누군가에게 유용 할 것입니다.
val text = resources.openRawResource(R.raw.your_text_file)
.bufferedReader().use { it.readText() }
- 1. Android 애플리케이션에서지도 애플리케이션 사용
- 2. Android : 애플리케이션 리소스 사용
- 3. 리소스에서 속성 파일 제외
- 4. 리소스에서 xml 파일 읽기
- 5. Android - URL에서 JSON 파일 다운로드
- 6. WCF를 사용하는 Android 애플리케이션
- 7. Android : TextView를 클릭하면 원시 리소스에서 mp3 파일 재생
- 8. Android 애플리케이션 아키텍처 - xml 파일 탐색
- 9. 애플리케이션 Early Flush JSON 형식
- 10. Android 애플리케이션 업데이트 - 방법?
- 11. haskell의 Android 애플리케이션
- 12. Android : 애플리케이션 또는 별도의 스레드 내에서 HTTP/JSON 통신이 가능합니까?
- 13. Android 기기에서 Android 애플리케이션 배포
- 14. Android 애플리케이션 완료 문제
- 15. Android 환경에서 파싱 된 500KB json 파일
- 16. Android : 내 파일 사용 방법
- 17. 모바일 애플리케이션 개발을위한 JSON 스키마
- 18. Android 리소스에서 문자열 값을 구분하지 않습니다.
- 19. 리소스에서 오디오를 재생하는 방법
- 20. 서명지도 애플리케이션 android
- 21. Android 동기화 애플리케이션
- 22. Android 위저드 (단계별) 애플리케이션
- 23. Android 보안 애플리케이션
- 24. Android 맞춤 GPS지도 애플리케이션
- 25. Android 애플리케이션 아이콘 변경
- 26. Android 애플리케이션 APK 서명?
- 27. Android 애플리케이션 프로그래밍 :
- 28. android : manifest.xml 애플리케이션 노드
- 29. 브랜드 가능 Android 애플리케이션
- 30. Android 애플리케이션 도움말
안드로이드의 String 리소스에 문자열을 넣고 getResources(). getString (R.String.name)을 사용하여 동적으로 사용하려면 어떻게해야합니까? –
나에게 그것은 따옴표 때문에 읽기에는 무시되고 또한 도망 칠 수없는 것처럼 작동하지 않는다. –
[ButterKnife] (http://jakewharton.github.io/butterknife/)를 만들 수있는 방법이 있습니까?) 원시 자원을 바인드합니까? 문자열을 읽는 데 단지 10 줄 이상의 코드를 작성하는 것은 조금 지나치게 과장된 것처럼 보입니다. – Jezor