我想使用Volley将这种类型的数据从android应用程序发送到我在IBM Watson-Studio中部署的机器学习模型API。
{
"fields":[
"Gender",
"Age",
"EstimatedSalary"
],
"values":[
Gender,
Age,
EstimatedSalary
]
}我一直在为这个需求创建一个JSON-Object并将其发送到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();
}发布于 2019-06-27 23:11:48
在构建了一个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);https://stackoverflow.com/questions/56793173
复制相似问题