A.J A.J - 1 month ago 7
Android Question

passing JSON object to a web service through AsyncTask

I am trying to pass a

JSON
object to a web service through
Asynctask
. I call a
collectStatistics
method in the
MainActivity
. This method collects some statistics of the mobile device and combines them together in a
JSON
object.
JSON
object is then passed to
Asynctask
.

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


The Asynctask receives JSON parameter

class SendJsonProperties extends AsyncTask <JSONObject,String,String>


I call a web service caller method in 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;
}


But I get this error

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


I cannot figure out the problem in serialization. Any help will be much appreciated. Thanks in advance.

A.J A.J
Answer

I was trying to send a JSON object to a web method which takes a string parameter

public string storeStatistics(string jsonObj)

So I changed

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

to

jsonProp.type = PropertyInfo.STRING_CLASS;
request.addProperty(jsonProp, obj.toString());