Android: JsonWriter can not write to a file

旧街凉风 提交于 2019-12-11 09:09:28

问题


i'm trying to call a JsonWriter method to add something to test.json after receiving wifi information, but after it successful write the file, the file still empty.Here are the codes.

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

the expected result should like

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

回答1:


you forget to call JsonWriter.close(); after writing JSONObject do it as:

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


来源:https://stackoverflow.com/questions/19277529/android-jsonwriter-can-not-write-to-a-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!