¿Cómo puedo escribir mis datos JSON para almacenamiento externo

programmer10:

Quiero escribir mi Arraylist de almacenamiento externo. El archivo debe estar en formato JSON.

FILE_NAME = notes.json

private boolean isExternalStorageWritable(){
    if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
        System.out.println("Storage is writeable");
        return true;
    }
    else{
        return false;
    }
}
 private void wirteFile(){
    if(isExternalStorageWritable()){
        File textFile = new File(Environment.getExternalStorageDirectory(), FILE_NAME);
        try{
            FileOutputStream fos = new FileOutputStream(textFile);
            fos.write(arrlist.toString().getBytes());
            fos.close();

        }catch (IOException e){
            e.printStackTrace();
        }

    }
}
Bruno:

Usted tiene que transformar su primera ArrayList en un JSONObject. Entonces, simplemente llame toString()método en el objeto creado.

if (isExternalStorageWritable()) {
  File file = new File(Environment.getExternalStorageDirectory(), FILE_NAME);
  JSONObject jsonObject = fromArrayList(arrayList); // you have to develop it

  try {
    Writer output = new BufferedWriter(new FileWriter(file));
    output.write(jsonObject.toString());
    output.close();
  } catch (IOException e) {
    e.printStackTrace();
  }
}

con FileOutputStream

  try {
    FileOutputStream output = new FileOutputStream(file);
    output.write(jsonObject.toString().getBytes());
    output.close();
  } catch (IOException e) {
    e.printStackTrace();
  }
}

Os pongo un ejemplo, para convertir sus datos en JSONObject

public class ListItem {
    private int id;
    private String name;

    public ListItem(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public JSONObject toJSONObject() {
        JSONObject object = new JSONObject();
        try {
            object.put("Id", id);
            object.put("Name", name);
        } catch (JSONException e) {
            trace("JSONException: "+e.getMessage());
        }
        return object;
    }
}

Y entonces,

public JSONObject fromArrayList(ArrayList<ListItem> arrayList) {
  JSONObject object = new JSONObject();
  JSONArray jsonArray = new JSONArray();
  for (int i=0; i < arrayList.size(); i++) {
    jsonArray.put(arrayList.get(i).toJSONObject());
  }
  object.put("result", jsonArray);
  return object;
}

Supongo que te gusta

Origin http://43.154.161.224:23101/article/api/json?id=318974&siteId=1
Recomendado
Clasificación