2

I want to send this type of data to my deployed machine learning model API in IBM Watson-Studio from an android application using Volley.

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

I'm stuck at creating a JSON-Object for this requirement and send it to the API.

I'm stuck at creating the JSON-Object and couldn't proceed

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

I know that doesn't work. But don't understand how to proceed.

Prashanthv
  • 109
  • 7
  • Your `fields` and `values` are `json array` ,also does value will remain same ? – Swati Jun 27 '19 at 14:41
  • @Swati Thanks and Yes, I'm trying to build a JSON array now. Don't worry about those values, they are just names of the variables – Prashanthv Jun 27 '19 at 14:51

1 Answers1

0

I've got the answer after building a JSONArray. In case if someone has the same question, here is the answer.

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);
Prashanthv
  • 109
  • 7