2015-08-20 47 views
0

我需要發送一個包含string,integerdouble數據混合的json對象到MongoDB。需要從Android發佈JSON對象

問題是我無法將對象從我的Activity發送到我用於連接並將數據發佈到MongoDB服務器的服務。

mJsonObject = new JSONObject(); 
    intentService = new Intent(); 
      intentService.setClass(this, MyService.class); 
      intentService.putExtra("Json Object", mJsonObject); 

編譯器不會讓我的意圖putExtra使用。

回答

0

Intent不接受一個JSONObjects,所以你必須把它轉換爲另一種數據類型比通過額外的意圖被髮送,如String:

intentService.putExtra("Json Object", mJsonObject.toString()); 

,然後將其從在接收時轉換回StringJSONObject

+1

謝謝穆罕默德,您的解決方案滿足了我的需求......! – Nikhil

+0

你很歡迎Nikhil,很高興我能幫忙:) –

0

您不能使用intent發送正常對象,要使用intent將對象從一個活動發送到另一個活動,Object必須是可序列化的。

So you can put data of Json Object into your custom pojo class which should implements serializable.then this pojo class object you can pass with intent 
0

JSONObject類未實現Serializable,所以你不能在意圖putExtra()方法添加。 但是你可以用以下兩種變通辦法此:

  1. 使用toString()JSONObject方法,並且此字符串添加到意圖。

  2. 只是延長JSONObjectJSONArray和實施Serializable,但請確保您已在子類中定義所有構造和實施返回父類型,如getJSONObject()getJSONArray()具體方法。