【问题标题】:passing JSON object to a web service through AsyncTask通过 AsyncTask 将 JSON 对象传递给 Web 服务
【发布时间】:2016-10-26 00:43:55
【问题描述】:

我正在尝试通过AsynctaskJSON 对象传递给Web 服务。我在MainActivity 中调用了collectStatistics 方法。此方法收集移动设备的一些统计信息,并将它们组合在一个JSON 对象中。然后将JSON 对象传递给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");
        }
    }

Asynctask 接收 JSON 参数

class SendJsonProperties extends AsyncTask <JSONObject,String,String>

我在 doInBackground 中调用了一个 Web 服务调用者方法

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

但我收到此错误

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

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

【问题讨论】:

    标签: android json web-services android-asynctask


    【解决方案1】:

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

    http://www.jsonschema2pojo.org/

    【讨论】:

    • 对不起,我不知道你在说什么,你能解释一下吗?感谢您的帮助。
    • 您收到此错误是因为您的对象(_product)未序列化。为此,您必须将其转换为可序列化,通过使用上面的链接,您可以获得序列化对象
    【解决方案2】:

    我试图将一个 JSON 对象发送到一个带有字符串参数的 Web 方法

    public string storeStatistics(string jsonObj)

    所以我改变了

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

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

    【讨论】:

      猜你喜欢
      • 2012-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-01
      • 1970-01-01
      相关资源
      最近更新 更多