1

我正在尝试JsonWriter在接收到wifi信息后调用一个方法向test.json添加一些东西,但是在它成功写入文件后,文件仍然是空的。这里是代码。

接收

 @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": "",
}
4

1 回答 1

4

JsonWriter.close();你在写完后忘记打电话JSONObject

        writer.name("status").value("OK");
        writer.name("num_results").value("");
        writer.endObject();
        writer.close();  //<<< call close here
于 2013-10-09T16:35:50.327 回答