我有一个自定义的GSON请求,我只想在请求中添加嵌套的params。我尝试了不同的方法,但它没有工作,意外的响应代码422,我不知道我做错了什么。我在这里添加我的代码。
自定义请求类
public CommunicationRequest(int method, String url, Class<T> clazz, Map<String, String> headers,
Response.Listener<T> listener, Response.ErrorListener errorListener, JSONObject json) {
super(method, url, errorListener);
this.clazz = clazz;
this.listener = listener;
this.headers = headers;
this.json = json;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
return headers != null ? headers : super.getHeaders();
}
@Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
try {
String json = new String(
response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(
gson.fromJson(json, clazz),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JsonSyntaxException e) {
return Response.error(new ParseError(e));
}
}
@Override
protected void deliverResponse(T response) {
listener.onResponse(response);
}
@Override
public byte[] getBody() throws AuthFailureError {
return json == null ? super.getBody() : json.toString().getBytes();
}
JSON格式
{"client_id": "",
"client_secret": "",
"user":{
"email": "test123@gmail.com",
"password": "12345678",
"password_confirmation": "12345678",
"first_name": "Test",
"last_name": "Last",
"mobile_phones_attributes": [
{
"number": "1234567890",
"type": "Mobile"
}
]
}
}
请求格式
CommunicationRequest<DataObject> request = new CommunicationRequest<DataObject>(Request.Method.POST,
uri,
EmailValidObject.class, headers, this, this,params) ;
我正在以json格式制作JSONObject
并将其传递给请求。
JSONObject params = new JSONObject();
JSONObject user = new JSONObject();
JSONObject mob = new JSONObject();
JSONArray mob_att = new JSONArray();
try {
params.put("client_id", "some_client_id");
params.put("client_secret", "some_client_secret");
user.put("email", "testiunn@gmail.com");
user.put("password", "12345678");
user.put("password_confirmation", "12345678");
user.put("first_name", "test first");
user.put("last_name", "test last");
mob.put("number", "+1 (123) 122-2123");
mob.put("type", "Mobile");
mob_att.put(mob);
user.put("mobile_phones_attributes", mob_att);
params.put("user", user);
} catch (JSONException e) {
e.printStackTrace();
}