【问题标题】:How do I use volley to post json object to Watson Studio API如何使用 volley 将 json 对象发布到 Watson Studio API
【发布时间】:2019-11-09 14:26:30
【问题描述】:

我想从一个使用 Volley 的 Android 应用程序将此类数据发送到我在 IBM Watson-Studio 中部署的机器学习模型 API。

{
   "fields":[
      "Gender",
      "Age",
      "EstimatedSalary"
   ],
   "values":[
      Gender,
      Age,
      EstimatedSalary
   ]
}

我一直坚持为此要求创建 JSON 对象并将其发送到 API。

我一直在创建 JSON 对象,无法继续

protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("fields","Gender");
                params.put("values",Gender);
                return super.getParams();
            }

我知道那行不通。但不明白如何进行。

【问题讨论】:

  • 你的fieldsvaluesjson array ,值也保持不变吗?
  • @Swati 谢谢,是的,我现在正在尝试构建一个 JSON 数组。不用担心这些值,它们只是变量的名称

标签: java android json android-volley watson-studio


【解决方案1】:

我在构建 JSONArray 后得到了答案。如果有人有同样的问题,这里是答案。

JSONObject  jsonObject=new JSONObject();
        try {
            JSONArray jsonArrayFields=new JSONArray();
                jsonArrayFields.put("Age");
                jsonArrayFields.put("Gender");
                jsonArrayFields.put("EstimatedSalary");

            jsonObject.put("results",jsonArrayFields);

            JSONArray jsonArrayValues = new JSONArray();
                jsonArrayValues.put(Age);
                jsonArrayValues.put(Gender);
                jsonArrayValues.put(EstimatedSalary);

            JSONArray jsonArrayValues2D = new JSONArray();
                jsonArrayValues2D.put(jsonArrayValues); //surrounding the jsonArrayValues in another Array

            jsonObject.put("values",jsonArrayValues2D);

        } catch (JSONException e) {
            e.printStackTrace();
        }

//and finally to send to the API
 JsonObjectRequest request_json = new JsonObjectRequest(Request.Method.POST, url, jsonObject,
           new Response.Listener<JSONObject>() {
               @Override
               public void onResponse(JSONObject response) {
                   try {
                       //on successful response
                   } catch (JSONException e) {
                       e.printStackTrace();
                   }
               }
           }, new Response.ErrorListener() {
               @Override
               public void onErrorResponse(VolleyError error) {
                   VolleyLog.e("Error: ", error.getMessage());
               }
           });

    // add the request object to the queue to be executed
    RequestQueue queue = Volley.newRequestQueue(this);
    queue.add(request_json);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-25
    • 2014-11-06
    • 2015-10-14
    • 2015-03-22
    • 1970-01-01
    • 2015-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多