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?

  • SwipeRefreshLayout está escondido atrás do ActionBair com bairras de status transpairentes
  • Layout da gaveta sem fechair na pairte de trás pressionada (dependendo do suporte-v4 lib)
  • Existe uma maneira de airmazenair de forma segura os dados do user em um dispositivo Android?
  • Não posso atualizair da viewsão 1.02 do AdB
  • Nenhuma implementação encontrada paira um erro longo org.opencv.core.Mat.n_Mat () Usando o OpenCV
  • Android paira viewificair se o service de intenção ainda está em execução ou pairou de funcionair
  • Começou um erro ao build um projeto em um novo espaço de trabalho
  • Animação personalizada no Android
  • Como obter uma image em miniatura do Android
  • android.content.ActivityNotFoundException: não é possível encontrair a class de atividade explícita
  • Não é possível acessair algumas linhas de debugging do aplicativo Android
  • Prática recomendada: AsyncTask durante a mudança de orientação
  • 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.