Usando o file JSON em resources de aplicativos paira Android

Suponha que eu tenho um file com conteúdo JSON na pasta de resources brutos no meu aplicativo. Como posso ler isso no aplicativo, paira que eu possa analisair o JSON?

  • Como definir uma etiqueta Fragment por código?
  • Seleção do Android selecionávelItemBackground
  • sem gravidade paira scrollview. como fazer conteúdo dentro do scrollview como centro
  • A connection ao adb está desativada e ocorreu um erro grave
  • Como limitair os itens da list exibidos no ListView por 10 e no próximo 10 depois clicando no button seguinte
  • Cairregando o file html paira o webview no android da pasta de resources usando o Android Studio
  • "Tel", "sms" e "mailto" não funcionam mais no Android após a atualização paira o cordova 3.6.3
  • Função PBKDF2 no Android
  • Datepicker: Como exibir pop-up datepicker quando clicair no button e airmazenair valor na vairiável
  • Conexão nativa no cliente Android
  • Android: Como desenhair direções de routes google maps API V2 da localization atual paira o destino
  • quando usair JNIEXPORT e JNICALL no Android NDK?
  • 5 Solutions collect form web for “Usando o file JSON em resources de aplicativos paira Android”

    Veja openRawResource . Algo assim deve funcionair:

    InputStream is = getResources().openRawResource(R.raw.json_file); Writer writer = new StringWriter(); chair[] buffer = new chair[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(); 

    Eu usei a resposta do @ kabuko paira criair um object que é cairregado a pairtir de um file JSON, usando o Gson , dos Recursos:

     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. * * @pairam resources An application {@link Resources} object. * @pairam 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. * * @pairam 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); } } importair java.io. *; 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. * * @pairam resources An application {@link Resources} object. * @pairam 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. * * @pairam 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); } } * / 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. * * @pairam resources An application {@link Resources} object. * @pairam 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. * * @pairam 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); } } * / 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. * * @pairam resources An application {@link Resources} object. * @pairam 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. * * @pairam 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); } } } 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. * * @pairam resources An application {@link Resources} object. * @pairam 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. * * @pairam 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); } } } catch (Exception e) { 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. * * @pairam resources An application {@link Resources} object. * @pairam 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. * * @pairam 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); } } } catch (Exception e) { 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. * * @pairam resources An application {@link Resources} object. * @pairam 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. * * @pairam 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); } } } 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. * * @pairam resources An application {@link Resources} object. * @pairam 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. * * @pairam 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); } } } 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. * * @pairam resources An application {@link Resources} object. * @pairam 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. * * @pairam 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); } } } 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. * * @pairam resources An application {@link Resources} object. * @pairam 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. * * @pairam 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); } } * / 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. * * @pairam resources An application {@link Resources} object. * @pairam 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. * * @pairam 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); } } } 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. * * @pairam resources An application {@link Resources} object. * @pairam 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. * * @pairam 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); } } 

    Paira usá-lo, você fairia algo como o seguinte (o exemplo é em um InstrumentationTestCase ):

      @Oviewride public void setUp() { // Load our JSON file. JSONResourceReader reader = new JSONResourceReader(getInstrumentation().getContext().getResources(), R.raw.jsonfile); MyJsonObject jsonObj = reader.constructUsingGson(MyJsonObject.class); } 

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

    cru/
    Arquivos airbitrários paira save em sua forma bruta. Paira abrir esses resources com um InputStream raw, chame Resources.openRawResource () com o ID do recurso, que é R.raw.filename.

    No entanto, se você precisair acessair nomes de files originais e hierairquia de files, você pode considerair save alguns resources no diretório de ativos / (em vez de res / raw /). Os files nos ativos / não recebem uma ID de recurso, paira que você possa lê-los usando o AssetManager.

    Kotlin agora é um idioma oficial paira o Android, então eu acho que isso seria útil paira alguém

     val text = resources.openRawResource(R.raw.your_text_file) .bufferedReader().use { it.readText() } 
     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"); 
    Android is Google's Open Mobile OS, Android APPs Developing is easy if you follow me.