2016-10-26 113 views
1

我试图通过AsynctaskJSON对象传递给Web服务。我在MainActivity中调用collectStatistics方法。此方法收集移动设备的一些统计信息,并将它们组合在一起,形成JSON对象。 JSON然后将对象传递给Asynctask通过AsyncTask将JSON对象传递给Web服务

JSONObject jsonProperties = new JSONObject(); 
    try { 
     jsonProperties.put("_device" , _device); 
     jsonProperties.put("_model", _model); 
     jsonProperties.put("_product", _product); 

    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 
    if (jsonProperties.length() > 0) 
    { 
     //call to async class 
     //String.valueOf(jsonProperties) 
     //new SendJsonProperties().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, jsonProperties); //instead of execute 
     Toast.makeText(context,jsonProperties.toString(),Toast.LENGTH_LONG).show(); 
     if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { 
      new SendJsonProperties().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, jsonProperties); 
      Log.i("msg","calling asynctask"); 
     } else { 
      new SendJsonProperties().execute(jsonProperties); 
      Log.i("msg","NOT calling asynctask"); 
     } 
    } 

该接收的AsyncTask JSON参数

class SendJsonProperties extends AsyncTask <JSONObject,String,String> 

我调用doInBackground

protected String doInBackground(JSONObject... params) 
{ 
    //(...) elippsis make the input array 
    Log.i("msg", "do in bkgnd"); 
    WebServicesCaller webServicesCaller = new WebServicesCaller(); 
    result = webServicesCaller.storeStatistics(params[0]); 
    return null; 
} 

Web服务调用者的方法,但我得到这个错误

java.lang.RuntimeException: Cannot serialize: {"_product":"ms013gxx","_model":"SM-G7102","_device":"ms013g"} 

我无法弄清楚序列化中的问题。任何帮助都感激不尽。提前致谢。

回答

0

我试图JSON对象发送到它需要一个字符串参数

public string storeStatistics(string jsonObj)

因此,我改变

jsonProp.setType(JSONObject.class); 
request.addProperty(jsonProp, obj); 

jsonProp.type = PropertyInfo.STRING_CLASS; 
request.addProperty(jsonProp, obj.toString()); 
一个Web方法
0

您必须为您的JSONObject参数创建Model POJO类。 使用此链接根据JSON REsponse创建POJO类。

http://www.jsonschema2pojo.org/

+0

对不起,但我不知道你在说什么,你能解释一下吗?谢谢你的帮助。 –

+0

你得到了这个错误,因为你的对象(_product)没有被序列化。为此,您必须将其转换为可串行化,通过使用上面的链接,您可以获得序列化的对象 –

相关问题