【发布时间】:2016-04-13 09:05:14
【问题描述】:
我有一个类组合JSON。该类有一个调用 makeJSONObject 的方法,它创建一个 JSON-Object 并将内容放入其中。这是类的代码。
public class CompositionJso extends JSONObject {
public JSONObject makeJSONObject (String title, String desc, ArrayList<String> imgPath, ArrayList<Resources> 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 变量并在其上调用 toString 吗?
-
好的,谢谢,现在可以正常使用了!
标签: android json filewriter