2013-10-09 98 views
1

我試圖調用JsonWriter方法在接收到wifi信息後向test.json添加內容,但在成功寫入文件後,文件仍爲空。這裏是代碼。Android:JsonWriter無法寫入文件

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

回答

3

你忘了寫JSONObject後打電話到JsonWriter.close();做得一樣:

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

如果我想執行或調用服務器上的外部文件。我該怎麼做? – dhpratik