我有一个接收参数并返回json作为响应的服务。响应json如下所示
{
"status": 0,
"message": "You are successfully registered",
"user": [
{
"name": "Rajiv",
"dob": "10/12/1988",
"gender": 1,
"qualification": "1",
"streams": "1",
"contactno": "3423234333",
"email": "rajiv88@gmail.com",
"password": "testpass",
"api_key": "29b9522d1bd23161db5aba89933a6015",
"profilepic": "NA",
"phverified": 0,
"emverified": 0,
"active": 0
}
]
}
我已经编写了如下界面:
@FormUrlEncoded
@POST("v20/register")
Call<RegisterResponse> insertUser(
@Field("name_of_user") String name,
@Field("dob") String dob,
@Field("gender") int gender,
@Field("qualification") String qualification,
@Field("streams") String streams,
@Field("contactno") String contactno,
@Field("email") String email,
@Field("password") String password);
注册响应类别如下
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import com.sbs.data.User;
public class RegisterResponse {
@SerializedName("status")
@Expose
private Integer status;
@SerializedName("message")
@Expose
private String message;
@SerializedName("user")
@Expose
private List<User> user = null;
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<User> getUser() {
return user;
}
public void setUser(List<User> user) {
this.user = user;
}
}
我按如下方式调用服务函数:
Call<RegisterResponse> call=jobApiService.insertUser(edName.getText().toString(),
edDob.getText().toString(),
spnGender.getSelectedItemPosition()+1,
categoryIDString, subCategoryIDString, txtPhone.getText().toString(), edmail.getText().toString(),
edpass.getText().toString());
call.enqueue(new Callback<RegisterResponse>() {
@Override
public void onResponse(Call<RegisterResponse> call, Response<RegisterResponse> response) {
Log.d("hj", "Number of users received: " + response.body().getMessage());
}
@Override
public void onFailure(Call<RegisterResponse> call, Throwable throwable) {
Log.d("hj", "Error");
}
});
但是我收到
NullPointerException
此陈述时
Log.d(“ hj”,“接收的用户数:” + response.body()。getMessage());
执行。
有人可以提出解决方案吗
答案 0 :(得分:0)
检查是否从远程服务器得到响应。如果为null,则使用邮差或其他任何工具分别测试您的api。如果可行,请检查您的请求代码。
public void onResponse(Call<RegisterResponse> call, Response<RegisterResponse> response) {
if(resonse.body != null && !TextUtils.isEmpty(response.body().getMessage())){
Log.d("hj", "Number of users received: " + response.body().getMessage());
} else {
Log.d("hj", "response received is null, but why??");
}
}
答案 1 :(得分:0)
尝试为列表用户删除初始化器null。
答案 2 :(得分:0)
我们已经以这种方式发送数据
身体类型-> 原始 对于这种类型,我们已经在模型中发送数据
@POST("user")
fun userInsert(@Body userModel: UserRequestModel): Observable<Response>
{
"email": "abcd@abcd.com",
"password": "123123"
}
身体类型-> x-www-form-urlencoded 这样的
@POST("user")
fun userInsert(@Body userHm: HashMap<String,String>): Observable<Response>
Hasmap <String, String> hm =new Hasmap<>()
hm.put("Key", value)
身体类型-> 表单数据 多部分需要此类型