天天看點

Android程式設計讀寫json檔案,android – 将JSON寫入檔案

我有一個類compositionJSON.該類有一個方法調用makeJSONObject,它建立一個JSON-Object并将東西放入其中.這是該類的代碼.

public class CompositionJso extends JSONObject {

public JSONObject makeJSONObject (String title, String desc, ArrayList imgPath, ArrayList imgView) {

JSONObject obj = new JSONObject() ;

try {

obj.put("title", title);

obj.put("desc", desc);

obj.put("imgPath", imgPath);

obj.put("imgViewPath", imgView);

} catch (JSONException e) {

e.printStackTrace();

}

return obj;

}

現在我建立這個類的一個執行個體,并在另一個類中調用該方法.之後我想将JSONObject寫入檔案并将其儲存在裝置上的SD卡上.這是代碼:

saveCompo.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

setName();

createJSONFolder();

CompositionJso obj = new CompositionJso();

obj.makeJSONObject(compoTitle, compoDesc, imgPaths, imageViewPaths);

MyCompositionsListActivity.buildList();

try {

Writer output = null;

File file = new File("storage/sdcard/MyIdea/MyCompositions/" + compoTitle + ".json");

output = new BufferedWriter(new FileWriter(file));

output.write(obj.toString());

output.close();

Toast.makeText(getApplicationContext(), "Composition saved", Toast.LENGTH_LONG).show();

} catch (Exception e) {

Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();

}

finish();

}

});

該檔案已成功儲存但如果我打開它,則内部沒有任何内容.代碼有什麼問題?

解決方法:

makeJSONObject傳回JSONObject

你的代碼應該是

saveCompo.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

setName();

createJSONFolder();

CompositionJso obj = new CompositionJso();

JSONObject jsonObject = obj.makeJSONObject(compoTitle, compoDesc, imgPaths, imageViewPaths);

MyCompositionsListActivity.buildList();

try {

Writer output = null;

File file = new File("storage/sdcard/MyIdea/MyCompositions/" + compoTitle + ".json");

output = new BufferedWriter(new FileWriter(file));

output.write(jsonObject.toString());

output.close();

Toast.makeText(getApplicationContext(), "Composition saved", Toast.LENGTH_LONG).show();

} catch (Exception e) {

Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();

}

finish();

}

});

标簽:android,json,filewriter

來源: https://codeday.me/bug/20190930/1837179.html