Android:JsonWriter无法写入文件

时间:2013-10-09 16:24:59

标签: java android json writer

我正在尝试调用JsonWriter方法在收到wifi信息后向test.json添加内容,但在成功写入文件后,该文件仍为空。这是代码。

的onReceive

 @Override
        public void onReceive(Context c, Intent i) {
            if (i.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION))
            {
                dbhelp = new DataBaseHelper(c);
                wifilist = new ArrayList<ScanResult>();
                wifilist = ((WifiManager) c.getSystemService(Context.WIFI_SERVICE)).getScanResults();
                dialog.dismiss();
                file = new File(c.getExternalCacheDir(),"testJson.json");           
                try
                {
                    out = new FileOutputStream(file);
                    writeJson(out);
                }
                catch(IOException e)
                {
                    e.printStackTrace();
                }
            }
        }

JsonWriter

public void writeJson(OutputStream out) throws IOException {
        writer = new JsonWriter(new OutputStreamWriter(out, "UTF-8"));
        writer.setIndent("    ");
        jsonFinal(writer);}

public void jsonFinal(JsonWriter writer) throws IOException{
            writer.beginObject();
            writer.name("status").value("OK");
            writer.name("num_results").value("");
            writer.endObject();
         }

预期结果应该

{
    "status": "OK",
    "num_results": "",
}

1 个答案:

答案 0 :(得分:3)

您在写JsonWriter.close();之后忘记致电JSONObject

        writer.name("status").value("OK");
        writer.name("num_results").value("");
        writer.endObject();
        writer.close();  //<<< call close here