gpt4 book ai didi

java - 如何将 JSON 数据写入外部存储

转载 作者:行者123 更新时间:2023-12-01 17:54:36 25 4
gpt4 key购买 nike

我想将我的Arraylist写入外部存储。文件应为 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();
}

}
}

最佳答案

您必须首先将 ArrayList 转换为 JSONObject。然后,只需在创建的对象上调用toString()方法即可。

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();
}
}

使用文件输出流

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

我给你一个例子,将你的数据转换成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;
}
}

然后,

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;
}

关于java - 如何将 JSON 数据写入外部存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60743340/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com