2011-06-14 13 views

Respuesta

97

Ver openRawResource. Algo como esto debería funcionar:

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(); 
+1

¿Qué sucede si quiero poner la cadena en un recurso de Cadena en Android y usarla dinámicamente usando getResources(). GetString (R.String.name)? –

+0

Para mí no funciona debido a las comillas, que se ignoran al leer y que también parecen no se pueden escapar –

+1

¿Hay alguna manera de hacer [ButterKnife] (http://jakewharton.github.io/butterknife/) unir el recurso sin procesar? Escribir más de 10 líneas de código solo para leer una cadena parece un poco exagerado. – Jezor

10

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

/
archivos arbitrarios primas para guardar en su forma cruda. Para abrir estos recursos con un InputStream sin procesar, llame a Resources.openRawResource() con el ID del recurso, que es R.raw.nombre de archivo.

Sin embargo, si necesita acceder a nombres de archivo originales y jerarquía de archivos, puede considerar guardar algunos recursos en el directorio assets/(en lugar de res/raw /). Los archivos en activos/no tienen una ID de recurso, por lo que puede leerlos solo mediante AssetManager.

+1

Si quiero incrustar un archivo JSON en mi aplicación, ¿dónde debería ubicarlo? en la carpeta de activos o en la carpeta sin procesar? ¡Gracias! – Ricardo

18

Solía ​​respuesta de @ kabuko para crear un objeto que se carga desde un archivo JSON, utilizando Gson, a partir de los 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. 
    * 
    * @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); 
    } 
} 

Para usarlo, se había hacer algo como lo siguiente (el ejemplo está en una 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); 
    } 
+0

¡Genial :)! Gracias. – nikolaDev

+0

Muy buena forma reutilizable para lograr esto. ¡Gracias! – speedynomads

+0

No olvide agregar dependencias {compilar com.google.code.gson: gson: 2.8.2 '} en su archivo gradle – patrics

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

Kotli n es ahora el idioma oficial de Android, por lo que creo que sería útil para alguien

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