2015-08-20 135 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()具体方法。