Escribir archivo .json y leer ese archivo en Android

Im archivo de escritura .json y quiero leer ese archivo, pero el problema es, cuando intento leer el archivo entero como cadena que agrega el espacio antes y después de cada carácter y sólo porque de caracteres adicionales que no podía leer json.

El formato Json es

[{"description1":"The ThinkerA bronze sculpture by Auguste Rodin. It depicts a man in sober\nmeditation battling with a powerful internal struggle.","description2":"Steve JobsFounder of Apple, he is widely recognized as a charismatic pioneer of\nthe personal computer revolution.","description3":"Justin BieberBorn in 1994, the latest sensation in music industry with numerous\nawards in recent years."}] 

Pero da una respuesta weired como: [{"description 1": "T …..

Para recortar los espacios extra que se refieren a esto, pero stil didnt trabajo: Java cómo reemplazar 2 o más espacios con un solo espacio en la cadena y eliminar los espacios principales sólo

Estoy usando este codigo

 File folderPath = Environment.getExternalStorageDirectory(); File mypath=new File(folderPath, "description.json"); StringBuffer fileData = new StringBuffer(1000); BufferedReader reader = null; reader = new BufferedReader(new FileReader(mypath)); char[] buf = new char[1024]; int numRead=0; while((numRead=reader.read(buf)) != -1) { String readData = String.valueOf(buf, 0, numRead); fileData.append(readData); buf = new char[1024]; } String response = fileData.toString(); 

La cadena de "respuesta" contiene respuesta extraña

Así que ¿alguien puede ayudarme?

Para escribir en archivo, im usando:

 FileOutputStream fos = new FileOutputStream(mypath); DataOutputStream dos = new DataOutputStream(fos); dos.writeChars(response); 

WriteChars escribe cada carácter como dos bytes.

http://docs.oracle.com/javase/6/docs/api/java/io/DataOutputStream.html#writeChars(java.lang.String )

http://docs.oracle.com/javase/6/docs/api/java/io/DataOutputStream.html#writeChar(int )

 Writes a char to the underlying output stream as a 2-byte value, high byte first. If no exception is thrown, the counter written is incremented by 2. 

Escriba a continuación el método para escribir el archivo Json, Aquí params es un nombre de archivo y mJsonResponse es una respuesta del servidor.

Para crear archivos en la memoria interna de la aplicación

 public void mCreateAndSaveFile(String params, String mJsonResponse) { try { FileWriter file = new FileWriter("/data/data/" + getApplicationContext().getPackageName() + "/" + params); file.write(mJsonResponse); file.flush(); file.close(); } catch (IOException e) { e.printStackTrace(); } } 

Para leer datos del archivo Json, Aquí params es File Name.

 public void mReadJsonData(String params) { try { File f = new File("/data/data/" + getPackageName() + "/" + params); FileInputStream is = new FileInputStream(f); int size = is.available(); byte[] buffer = new byte[size]; is.read(buffer); is.close(); String mResponse = new String(buffer); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } 

Me gusta arriba de la respuesta y editado: Me encanta compartir, así que he compartido que puede ser útil a los demás.

Copie y pegue la siguiente clase en su paquete y use como:

Guardar: MyJSON.saveData(context, jsonData);

Leer: String json = MyJSON.getData(context);

 import android.content.Context; import android.util.Log; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; /** * Created by Pratik. */ public class MyJSON { static String fileName = "myBlog.json"; public static void saveData(Context context, String mJsonResponse) { try { FileWriter file = new FileWriter(context.getFilesDir().getPath() + "/" + fileName); file.write(mJsonResponse); file.flush(); file.close(); } catch (IOException e) { Log.e("TAG", "Error in Writing: " + e.getLocalizedMessage()); } } public static String getData(Context context) { try { File f = new File(context.getFilesDir().getPath() + "/" + fileName); //check whether file exists FileInputStream is = new FileInputStream(f); int size = is.available(); byte[] buffer = new byte[size]; is.read(buffer); is.close(); return new String(buffer); } catch (IOException e) { Log.e("TAG", "Error in Reading: " + e.getLocalizedMessage()); return null; } } } 

Su código de escritura es el problema. Solo usa

 FileWriter fos = new FileWriter(mypath); fos.write(response); 
  • Android: ¿Cómo url de la tienda en el archivo de recursos string.xml?
  • ¿Cómo inserto un salto de línea en una cadena para mostrarlo en un widget Android TextView?
  • Android Preferences error, "String no se puede convertir en int"
  • Cómo leer / escribir cadena de un archivo en Android
  • Cuerdas Android dependientes del tema
  • Fórmula química en Android
  • ¿Cómo referenciar una cadena de otro paquete en una biblioteca usando XML en Android?
  • ¿Qué hay de malo en la cadena hardcoded en el archivo xml android?
  • ¿Por qué la marquesina no funciona en Widget?
  • Cadena dinámica utilizando String.xml?
  • JUnit4 TextUtils.isEmpty () da un resultado diferente que String.isEmpty ()
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.