Am new to Retrofit and API Integration. Am trying to display response in a toast. Am using Retrofit for an API call. But the response from Retrofit is showing null . There is no response instead null. I don't Know may be am doing in a wrong way. Here is my code. Please Help me
Below is sample API
Params:
{
"DeviceID": "Hawqr-jagadish-test-device",
"DeviceType": "1",
"DeviceName": "Jagadish Device",
"AppVersion": 1
}
Response:
{
"success": true,
"extras": {
"Status": "Device Splash Screen Completed Successfully",
"Env_Type": 2,
"ApiKey": "4ae3a7e5-2622-4376-bc0d-a0ccd6c0405a",
"Whether_Latest_Version": true,
"SocketIO_Data": {
"socket_host": "https://xsocket.hawqr.com",
"socketjs_link": "https://xsocket.hawqr.com/socket.io/socket.io.js"
}
}
}
This My Main Activity. In main activity i have call API
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(MainActivity.this,LoginActivity.class);
startActivity(intent);
finish();
}
},SPLASH_SCREEN );
String DeviceID = "Hawqr-jagadish-test-device";
String DeviceType = "1";
String DeviceName = "Jagadish Device";
Integer AppVersion = 1 ;
SplashRequest splashRequest = new SplashRequest();
splashRequest.setDeviceID(DeviceID);
splashRequest.setDeviceType(DeviceType);
splashRequest.setDeviceName(DeviceName);
splashRequest.setAppVersion(AppVersion);
SplashScreen(splashRequest);
}
public void SplashScreen(SplashRequest splashRequest){
UserService userService = ApiClient.getRetrofit().create(UserService.class);
Call<SplashResponse> splashResponseCall = userService.splashScreen(splashRequest);
splashResponseCall.enqueue(new Callback<SplashResponse>() {
#Override
public void onResponse(Call<SplashResponse> call, Response<SplashResponse> response) {
Gson gson = new Gson();
String successResponse = gson.toJson(response.body());
Toast.makeText(MainActivity.this,successResponse,Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(Call<SplashResponse> call, Throwable t) {
String msg = t.getLocalizedMessage();
Toast.makeText(MainActivity.this,msg,Toast.LENGTH_SHORT).show();
}
});
}
}
These are my Model classes for Parameters
public class SplashRequest {
public String DeviceID;
public String DeviceType;
public String DeviceName;
public Integer AppVersion;
public String getDeviceID() {
return DeviceID;
}
public void setDeviceID(String deviceID) {
DeviceID = deviceID;
}
public String getDeviceType() {
return DeviceType;
}
public void setDeviceType(String deviceType) {
DeviceType = deviceType;
}
public String getDeviceName() {
return DeviceName;
}
public void setDeviceName(String deviceName) {
DeviceName = deviceName;
}
public Integer getAppVersion() {
return AppVersion;
}
public void setAppVersion(Integer appVersion) {
AppVersion = appVersion;
}
Another Model Class
public String ApiKey;
public String Env_Type;
public String Status;
public String Whether_Latest_Version;
public SplashResponse(String apiKey, String env_Type, String status, String whether_Latest_Version) {
ApiKey = apiKey;
Env_Type = env_Type;
Status = status;
Whether_Latest_Version = whether_Latest_Version;
}
public String getApiKey() {
return ApiKey;
}
public void setApiKey(String apiKey) {
ApiKey = apiKey;
}
public String getEnv_Type() {
return Env_Type;
}
public void setEnv_Type(String env_Type) {
Env_Type = env_Type;
}
public String getStatus() {
return Status;
}
public void setStatus(String status) {
Status = status;
}
public String getWhether_Latest_Version() {
return Whether_Latest_Version;
}
public void setWhether_Latest_Version(String whether_Latest_Version) {
Whether_Latest_Version = whether_Latest_Version;
}
}
This My Interface Class for Splash Response and Request
#POST("authenticate/")
Call<SplashResponse> splashScreen(#Body SplashRequest splashRequest);
The model class Splash Response was wrong, I made changes to it and its working fine.
public class SplashResponse implements Serializable {
#SerializedName("success")
#Expose
private Boolean success;
#SerializedName("extras")
#Expose
private Extras extras;
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public Extras getExtras() {
return extras;
}
public void setExtras(Extras extras) {
this.extras = extras;
}
public class Extras {
#SerializedName("Status")
#Expose
private String status;
#SerializedName("Env_Type")
#Expose
private Integer envType;
#SerializedName("ApiKey")
#Expose
private String apiKey;
#SerializedName("Whether_Latest_Version")
#Expose
private Boolean whetherLatestVersion;
#SerializedName("SocketIO_Data")
#Expose
private SocketIOData socketIOData;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Integer getEnvType() {
return envType;
}
public void setEnvType(Integer envType) {
this.envType = envType;
}
public String getApiKey() {
return apiKey;
}
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
public Boolean getWhetherLatestVersion() {
return whetherLatestVersion;
}
public void setWhetherLatestVersion(Boolean whetherLatestVersion) {
this.whetherLatestVersion = whetherLatestVersion;
}
public SocketIOData getSocketIOData() {
return socketIOData;
}
public void setSocketIOData(SocketIOData socketIOData) {
this.socketIOData = socketIOData;
}
#SerializedName("code")
#Expose
private Integer code;
#SerializedName("msg")
#Expose
private String msg;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
public class SocketIOData {
#SerializedName("socket_host")
#Expose
private String socketHost;
#SerializedName("socketjs_link")
#Expose
private String socketjsLink;
public String getSocketHost() {
return socketHost;
}
public void setSocketHost(String socketHost) {
this.socketHost = socketHost;
}
public String getSocketjsLink() {
return socketjsLink;
}
public void setSocketjsLink(String socketjsLink) {
this.socketjsLink = socketjsLink;
}
}
}
Next In My Main Activity I made these changes
public void SplashScreen(SplashRequest splashRequest){
UserService userService = ApiClient.getRetrofit().create(UserService.class);
Call<SplashResponse> splashResponseCall = userService.splashScreen(splashRequest);
splashResponseCall.enqueue(new Callback<SplashResponse>() {
#Override
public void onResponse(Call<SplashResponse> call, Response<SplashResponse> response) {
Gson gson = new Gson();
String successResponse = gson.toJson(response.body());
SplashResponse response1 = response.body();
if (response.isSuccessful()) {
Toast.makeText(MainActivity.this, response1.getExtras().getStatus(), Toast.LENGTH_LONG).show();
}else {
//Toast.makeText(MainActivity.this, response1.getExtras().getStatus(), Toast.LENGTH_LONG).show();
if(response1.getExtras().getCode() == 1){
Toast.makeText(MainActivity.this, response1.getExtras().getMsg(), Toast.LENGTH_LONG).show();
}else{
Toast.makeText(MainActivity.this, response1.getExtras().getMsg(), Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onFailure(Call<SplashResponse> call, Throwable t) {
String msg = t.getLocalizedMessage();
Toast.makeText(MainActivity.this,msg,Toast.LENGTH_SHORT).show();
}
});
}
Related
I am trying to making a POST request using retrofit2 but I am getting ErrorCode: 401. I am not finding the proper solution on the web that can help me out to solve my problem.
Data load for POST request
InsertAcitvity.java
private void insertData() {
String name = mName.getText().toString().trim();
String email = mEmail.getText().toString().trim();
String phone = mPhone.getText().toString().trim();
String full_address = mFull_address.getText().toString().trim();
String name_of_university = mName_of_university.getText().toString().trim();
int graduation_year = Integer.parseInt(mGraduation_year.getText().toString().trim());
double cgpa = Double.parseDouble(mCgpa.getText().toString().trim()) ;
String experience_in_months = mExperience_in_months.getText().toString().trim();
String current_work_place_name = mCurrent_work_place_name.getText().toString().trim();
String applying_in = mApplying_in.getText().toString().trim();
int expected_salary = Integer.parseInt(mExpected_salary.getText().toString().trim()) ;
String reference = mFeference.getText().toString().trim();
String github_project_url = mGithub_project_url.getText().toString().trim();
long creationTime= System.currentTimeMillis();
long updateTime= System.currentTimeMillis();
//String token = LoginActivity.token;
Intent intent = getIntent();
// declare token as member variable
String token = intent.getStringExtra("TOKEN_STRING");
String CvUniqueId = UUID.randomUUID().toString();
String tsync_id = UUID.randomUUID().toString();
cvFileObject = new CvFileObject(CvUniqueId);
mainObject = new MainObjectClass(tsync_id, name, email, phone, full_address, name_of_university, graduation_year, cgpa, experience_in_months,
current_work_place_name, applying_in, expected_salary,field_buzz_reference, github_project_url, cvFileObject, creationTime, updateTime);
ClientMethod clientMethod = ApiClient.getClient().create(ClientMethod.class);
Call<MainResponseObjectClass> call = clientMethod.getValue(token,mainObject);
call.enqueue(new Callback<MainResponseObjectClass>() {
#Override
public void onResponse(#NonNull Call<MainResponseObjectClass> call, #NonNull Response<MainResponseObjectClass> response) {
if (response.isSuccessful()){
Toast.makeText(InsertActivity.this, response.body().getTsync_id(), Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(InsertActivity.this, "access denied:(",Toast.LENGTH_LONG).show();
Log.d("ErrorCode", "onResponse: " + response.code());
}
}
#Override
public void onFailure(#NonNull Call<MainResponseObjectClass> call, #NonNull Throwable t) {
Log.d("Error", "onFailure: " + t.getMessage());
}
});
}
ClientMethod.java
public interface ClientMethod {
#POST("api/login/")
Call<Token>login(#Body Login login);
#POST("/api/v0/recruiting-entities/")
Call<MainResponseObjectClass> getValue(#Header("Authorization") String AutToken, #Body MainObjectClass mainObjectClass);
}
ApliClient.java
public class ApiClient {
public static final String BASE_URL = "https://myapi.test.com";
private static Retrofit retrofit = null;
public static Retrofit getClient(){
if (retrofit == null){
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
POST request code
CvFileObject.java
public class CvFileObject {
#SerializedName("tsync_id")
private String tsync_id;
public CvFileObject(String tsync_id) {
this.tsync_id = tsync_id;
}
public String getTsync_id() {
return tsync_id;
}
public void setTsync_id(String tsync_id) {
this.tsync_id = tsync_id;
}
}
MainObjectClass.java
public class MainObjectClass {
#SerializedName("tsync_id")
private String tsync_id;
#SerializedName("name")
private String name;
#SerializedName("email")
private String email;
#SerializedName("phone")
private String phone;
#SerializedName("full_address")
private String full_address;
#SerializedName("name_of_university")
private String name_of_university;
#SerializedName("graduation_year")
private int graduation_year;
#SerializedName("cgpa")
private double cgpa;
#SerializedName("experience_in_months")
private String experience_in_months;
#SerializedName("current_work_place_name")
private String current_work_place_name;
#SerializedName("applying_in")
private String applying_in;
#SerializedName("expected_salary")
private int expected_salary;
#SerializedName("reference")
private String reference;
#SerializedName("github_project_url")
private String github_project_url;
#SerializedName("cv_file")
private CvFileObject fileObject;
#SerializedName("on_spot_update_time")
long on_spot_update_time;
#SerializedName("on_spot_creation_time")
long on_spot_creation_time;
public MainObjectClass(String tsync_id, String name, String email, String phone, String full_address,
String name_of_university, int graduation_year, double cgpa, String experience_in_months,
String current_work_place_name, String applying_in, int expected_salary, String reference,
String github_project_url, CvFileObject fileObject, long on_spot_update_time, long on_spot_creation_time) {
this.tsync_id = tsync_id;
this.name = name;
this.email = email;
this.phone = phone;
this.full_address = full_address;
this.name_of_university = name_of_university;
this.graduation_year = graduation_year;
this.cgpa = cgpa;
this.experience_in_months = experience_in_months;
this.current_work_place_name = current_work_place_name;
this.applying_in = applying_in;
this.expected_salary = expected_salary;
this.reference = reference;
this.github_project_url = github_project_url;
this.fileObject = fileObject;
this.on_spot_update_time = on_spot_update_time;
this.on_spot_creation_time = on_spot_creation_time;
}
public String getTsync_id() {
return tsync_id;
}
public void setTsync_id(String tsync_id) {
this.tsync_id = tsync_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getFull_address() {
return full_address;
}
public void setFull_address(String full_address) {
this.full_address = full_address;
}
public String getName_of_university() {
return name_of_university;
}
public void setName_of_university(String name_of_university) {
this.name_of_university = name_of_university;
}
public int getGraduation_year() {
return graduation_year;
}
public void setGraduation_year(int graduation_year) {
this.graduation_year = graduation_year;
}
public double getCgpa() {
return cgpa;
}
public void setCgpa(double cgpa) {
this.cgpa = cgpa;
}
public String getExperience_in_months() {
return experience_in_months;
}
public void setExperience_in_months(String experience_in_months) {
this.experience_in_months = experience_in_months;
}
public String getCurrent_work_place_name() {
return current_work_place_name;
}
public void setCurrent_work_place_name(String current_work_place_name) {
this.current_work_place_name = current_work_place_name;
}
public String getApplying_in() {
return applying_in;
}
public void setApplying_in(String applying_in) {
this.applying_in = applying_in;
}
public int getExpected_salary() {
return expected_salary;
}
public void setExpected_salary(int expected_salary) {
this.expected_salary = expected_salary;
}
public String reference() {
return reference;
}
public void setreference(String reference) {
this.reference = reference;
}
public String getGithub_project_url() {
return github_project_url;
}
public void setGithub_project_url(String github_project_url) {
this.github_project_url = github_project_url;
}
public CvFileObject getFileObject() {
return fileObject;
}
public void setFileObject(CvFileObject fileObject) {
this.fileObject = fileObject;
}
public long getOn_spot_update_time() {
return on_spot_update_time;
}
public void setOn_spot_update_time(long on_spot_update_time) {
this.on_spot_update_time = on_spot_update_time;
}
public long getOn_spot_creation_time() {
return on_spot_creation_time;
}
public void setOn_spot_creation_time(long on_spot_creation_time) {
this.on_spot_creation_time = on_spot_creation_time;
}
}
POST request response code
CvFileResponseObject.java
public class CvFileResponseObject {
#SerializedName("id")
int id;
#SerializedName("tsync_id")
private String tsync_id;
public CvFileResponseObject(String tsync_id) {
this.tsync_id = tsync_id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTsync_id() {
return tsync_id;
}
public void setTsync_id(String tsync_id) {
this.tsync_id = tsync_id;
}
}
MainResponseObjectClass.java
public class MainResponseObjectClass {
#SerializedName("tsync_id")
private int tsync_id;
#SerializedName("name")
private String name;
#SerializedName("email")
private String email;
#SerializedName("phone")
private String phone;
#SerializedName("full_address")
private String full_address;
#SerializedName("name_of_university")
private String name_of_university;
#SerializedName("graduation_year")
private int graduation_year;
#SerializedName("cgpa")
private double cgpa;
#SerializedName("experience_in_months")
private String experience_in_months;
#SerializedName("current_work_place_name")
private String current_work_place_name;
#SerializedName("applying_in")
private String applying_in;
#SerializedName("expected_salary")
private String expected_salary;
#SerializedName("reference")
private String reference;
#SerializedName("github_project_url")
private String github_project_url;
#SerializedName("cv_file")
private CvFileResponseObject cvFileResponseObject;
#SerializedName("on_spot_update_time")
long on_spot_update_time;
#SerializedName("on_spot_creation_time")
long on_spot_creation_time;
#SerializedName("success")
private boolean success;
#SerializedName("message")
private String message;
public MainResponseObjectClass(int tsync_id, String name, String email, String phone,
String full_address, String name_of_university, int graduation_year,
double cgpa, String experience_in_months, String current_work_place_name,
String applying_in, String expected_salary, String reference,
String github_project_url, CvFileResponseObject cvFileResponseObject, long on_spot_update_time,
long on_spot_creation_time, boolean success, String message) {
this.tsync_id = tsync_id;
this.name = name;
this.email = email;
this.phone = phone;
this.full_address = full_address;
this.name_of_university = name_of_university;
this.graduation_year = graduation_year;
this.cgpa = cgpa;
this.experience_in_months = experience_in_months;
this.current_work_place_name = current_work_place_name;
this.applying_in = applying_in;
this.expected_salary = expected_salary;
this.reference = reference;
this.github_project_url = github_project_url;
this.cvFileResponseObject = cvFileResponseObject;
this.on_spot_update_time = on_spot_update_time;
this.on_spot_creation_time = on_spot_creation_time;
this.success = success;
this.message = message;
}
public int getTsync_id() {
return tsync_id;
}
public void setTsync_id(int tsync_id) {
this.tsync_id = tsync_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getFull_address() {
return full_address;
}
public void setFull_address(String full_address) {
this.full_address = full_address;
}
public String getName_of_university() {
return name_of_university;
}
public void setName_of_university(String name_of_university) {
this.name_of_university = name_of_university;
}
public int getGraduation_year() {
return graduation_year;
}
public void setGraduation_year(int graduation_year) {
this.graduation_year = graduation_year;
}
public double getCgpa() {
return cgpa;
}
public void setCgpa(double cgpa) {
this.cgpa = cgpa;
}
public String getExperience_in_months() {
return experience_in_months;
}
public void setExperience_in_months(String experience_in_months) {
this.experience_in_months = experience_in_months;
}
public String getCurrent_work_place_name() {
return current_work_place_name;
}
public void setCurrent_work_place_name(String current_work_place_name) {
this.current_work_place_name = current_work_place_name;
}
public String getApplying_in() {
return applying_in;
}
public void setApplying_in(String applying_in) {
this.applying_in = applying_in;
}
public String getExpected_salary() {
return expected_salary;
}
public void setExpected_salary(String expected_salary) {
this.expected_salary = expected_salary;
}
public String getField_buzz_reference() {
return field_buzz_reference;
}
public void setFeference(String reference) {
this.field_buzz_reference = reference;
}
public String getGithub_project_url() {
return github_project_url;
}
public void setGithub_project_url(String github_project_url) {
this.github_project_url = github_project_url;
}
public CvFileResponseObject getCvFileResponseObject() {
return cvFileResponseObject;
}
public void setCvFileResponseObject(CvFileResponseObject cvFileResponseObject) {
this.cvFileResponseObject = cvFileResponseObject;
}
public long getOn_spot_update_time() {
return on_spot_update_time;
}
public void setOn_spot_update_time(long on_spot_update_time) {
this.on_spot_update_time = on_spot_update_time;
}
public long getOn_spot_creation_time() {
return on_spot_creation_time;
}
public void setOn_spot_creation_time(long on_spot_creation_time) {
this.on_spot_creation_time = on_spot_creation_time;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
Here I can see two APIs. But I am not sure which to which API you are getting 401. I can help you with the possibilities that you could check and please feel free to ask.
Assuming you are getting 401 for login API - the reason could be you are trying with wrong credentials.
Assuming you are getting 401 for getValue API - the reason could be you might passing the wrong token which you got from login response. Especially you need to cross-check the header with key and values.
And I have one suggestion - you could use header in Interceptor with retrofit setup itself.
Im trying to post data with retrofit with jwt bearer authentication, but when i debug response code, its
error 400, and the message is body = null
This is my Intefrace class
#Headers({"accept: text/plain","Content-Type: application/json-patch+json" })
#POST("services/app/ProjectService/Create")
Call<ProjectRequest> postProject(#Header("Authorization") String token,
#Body ProjectRequest projectRequest
);
This is my model class
public class ProjectRequest {
#SerializedName("name")
#Expose
private String name;
#SerializedName("description")
#Expose
private String description;
#SerializedName("ownerId")
#Expose
private int ownerId;
#SerializedName("startPeriod")
#Expose
private String startPeriod;
#SerializedName("endPeriod")
#Expose
private String endPeriod;
#SerializedName("isDraft")
#Expose
private boolean isDraft;
#SerializedName("ownerName")
#Expose
private String ownerName;
#SerializedName("pitId")
#Expose
private int pitId;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getOwnerId() {
return ownerId;
}
public void setOwnerId(int ownerId) {
this.ownerId = ownerId;
}
public String getStartPeriod() {
return startPeriod;
}
public void setStartPeriod(String startPeriod) {
this.startPeriod = startPeriod;
}
public String getEndPeriod() {
return endPeriod;
}
public void setEndPeriod(String endPeriod) {
this.endPeriod = endPeriod;
}
public boolean isDraft() {
return isDraft;
}
public void setDraft(boolean draft) {
isDraft = draft;
}
public String getOwnerName() {
return ownerName;
}
public void setOwnerName(String ownerName) {
this.ownerName = ownerName;
}
public int getPitId() {
return pitId;
}
public void setPitId(int pitId) {
this.pitId = pitId;
}
And the main class is
private void initApi() {
projectApi = ApiClient.getClient().create(ProjectApi.class);
}
private void postProject(final boolean isOnline) {
if (isOnline) {
final ProjectRequest projectRequest = new ProjectRequest();
projectRequest.setName(projectName);
projectRequest.setDescription(description);
projectRequest.setOwnerId(1);
projectRequest.setStartPeriod(dateStart);
projectRequest.setEndPeriod(dateEnd);
projectRequest.setDraft(true);
projectRequest.setOwnerName("yogi kun");
projectRequest.setPitId(1);
Call<ProjectRequest> callProject = projectApi.postProject(" Bearer eyJ0eXAiOiJKV1QiLCJub25jZSI6Il and so . . . ",
projectRequest);
callProject.enqueue(new Callback<ProjectRequest>() {
#Override
public void onResponse(#NotNull Call<ProjectRequest> call, #NotNull Response<ProjectRequest> response) {
if (response.isSuccessful()) {
try {
Toast.makeText(getContext(), "Success", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
String message = "";
if (e.getMessage() != null) {
message = e.getMessage();
}
Toast.makeText(getContext(), "Failed " + message, Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getContext(), "Failed " + response, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(#NotNull Call<ProjectRequest> call, #NotNull Throwable t) {
Toast.makeText(getContext(), "Failure" + t, Toast.LENGTH_SHORT).show();
}
});
}
And the error is
enter image description here
And
enter image description here
Might be an issue with how the JSON is formatted, compared to what you're expecting. Are you able to use something like Postman and try this API call to see the format it comes back? Can't tell that much but the error message shown is finding some array somewhere in the JSON
The parsing is successful but problem is ,it is taking loggedinClients only,ActiveClients not getting in retrofit , how can we parse array under array and with no object name?
{
"status": 200,
"success": true,
"messages": "",
"result": [
[
{
"LoggedinClients": 1
}
],
[
{
"ActiveClients": 0
}
]
]
}
partly Related Code:
public class OnlineInfoResponse {
#SerializedName("result")
#Expose
private List<List<OnlineInfoLoggedInResult>> lstLists = null;
public List<List<OnlineInfoLoggedInResult>> getLstLoggedIn() {
return lstLists;
}
public void setLstLists(List<List<OnlineInfoLoggedInResult>> lstLists) {
this.lstLists = lstLists;
}
OnlineInfoLoggedInResult.java
public class OnlineInfoLoggedInResult {
#SerializedName("LoggedinClients")
#Expose
private int loggedinClients;
public int getLoggedinClients() {
return loggedinClients;
}
public void setLoggedinClients(int loggedinClients) {
this.loggedinClients = loggedinClients;
}
#SerializedName("ActiveClients")
#Expose
private int activeClients;
public int getActiveClients() {
return activeClients;
}
public void setActiveClients(int activeClients) {
this.activeClients = activeClients;
}
}
this i got parsing from jsonschema.I am having problem in nested jsonarray.
You should generate the following POJO
public class YourPojoName {
private float status;
private boolean success;
private String messages;
List <List< Object> > result = new ArrayList < ArrayList<Object> > ();
// Getter Methods
public float getStatus() {
return status;
}
public boolean getSuccess() {
return success;
}
public String getMessages() {
return messages;
}
// Setter Methods
public void setStatus(float status) {
this.status = status;
}
public void setSuccess(boolean success) {
this.success = success;
}
public void setMessages(String messages) {
this.messages = messages;
}
}
public class abbb {
#Expose
#SerializedName("result")
private List<List<Result>> result;
#Expose
#SerializedName("messages")
private String messages;
#Expose
#SerializedName("success")
private boolean success;
#Expose
#SerializedName("status")
private int status;
public List<List<Result>> getResult() {
return result;
}
public void setResult(List<List<Result>> result) {
this.result = result;
}
public String getMessages() {
return messages;
}
public void setMessages(String messages) {
this.messages = messages;
}
public boolean getSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public static class Result {
#Expose
#SerializedName("LoggedinClients")
private int LoggedinClients;
#Expose
#SerializedName("ActiveClients")
private int active_clients;
//genetrate getter setter
}
}
call.enqueue(new Callback<Resul>() {
#Override
public void onResponse(Call<Resul> call, Response<Resul> response) {
progressDialog.dismiss();
Log.d("response", "code = " + response.code());
Log.d("mvvvv","StudentId : "+response.body().toString());
String h=response.body().toString();
if("1".equals(h)){
Intent i = new Intent(Login.this,MainActivity.class);
startActivity(i);
}
else {
Toast.makeText(getApplicationContext()," user name not valid " , Toast.LENGTH_LONG).show();
}
}
Pojo class
package com.example.admin.myappl.Interface;
public class Resul {
private User_info user_info;
private Response Response;
public User_info getUser_info ()
{
return user_info;
}
public void setUser_info (User_info user_info)
{
this.user_info = user_info;
}
public Response getResponse ()
{
return Response;
}
public void setResponse (Response Response)
{
this.Response = Response;
}
public String toString() {
return ""+Response+"";
}
public class Response
{
private String response_message;
private String response_code;
public String getResponse_message ()
{
return response_message;
}
public void setResponse_message (String response_message)
{
this.response_message = response_message;
}
public String getResponse_code ()
{
return response_code;
}
public void setResponse_code (String response_code)
{
this.response_code = response_code;
}
#Override
public String toString()
{
return response_code;
}
}
public class User_info
{
private String profile_picture;
private String lastweek_command;
private String weight;
private String student_id;
private String push_notification_status;
private String id;
private String first_name;
private String updated_at;
private String height;
private String blood_group;
private String email;
private String address;
private String dob;
private String last_name;
private String gender;
private String general_command;
private String activity;
private String mobile_no;
public String getProfile_picture ()
{
return profile_picture;
}
public void setProfile_picture (String profile_picture)
{
this.profile_picture = profile_picture;
}
public String getLastweek_command ()
{
return lastweek_command;
}
public void setLastweek_command (String lastweek_command)
{
this.lastweek_command = lastweek_command;
}
public String getWeight ()
{
return weight;
}
public void setWeight (String weight)
{
this.weight = weight;
}
public String getStudent_id ()
{
return student_id;
}
public void setStudent_id (String student_id)
{
this.student_id = student_id;
}
public String getPush_notification_status ()
{
return push_notification_status;
}
public void setPush_notification_status (String push_notification_status)
{
this.push_notification_status = push_notification_status;
}
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
public String getFirst_name ()
{
return first_name;
}
public void setFirst_name (String first_name)
{
this.first_name = first_name;
}
public String getUpdated_at ()
{
return updated_at;
}
public void setUpdated_at (String updated_at)
{
this.updated_at = updated_at;
}
public String getHeight ()
{
return height;
}
public void setHeight (String height)
{
this.height = height;
}
public String getBlood_group ()
{
return blood_group;
}
public void setBlood_group (String blood_group)
{
this.blood_group = blood_group;
}
public String getEmail ()
{
return email;
}
public void setEmail (String email)
{
this.email = email;
}
public String getAddress ()
{
return address;
}
public void setAddress (String address)
{
this.address = address;
}
public String getDob ()
{
return dob;
}
public void setDob (String dob)
{
this.dob = dob;
}
public String getLast_name ()
{
return last_name;
}
public void setLast_name (String last_name)
{
this.last_name = last_name;
}
public String getGender ()
{
return gender;
}
public void setGender (String gender)
{
this.gender = gender;
}
public String getGeneral_command ()
{
return general_command;
}
public void setGeneral_command (String general_command)
{
this.general_command = general_command;
}
public String getActivity ()
{
return activity;
}
public void setActivity (String activity)
{
this.activity = activity;
}
public String getMobile_no ()
{
return mobile_no;
}
public void setMobile_no (String mobile_no)
{
this.mobile_no = mobile_no;
}
#Override
public String toString()
{
return "ClassPojo [profile_picture = "+profile_picture+", lastweek_command = "+lastweek_command+", weight = "+weight+", student_id = "+student_id+", push_notification_status = "+push_notification_status+", id = "+id+", first_name = "+first_name+", updated_at = "+updated_at+", height = "+height+", blood_group = "+blood_group+", email = "+email+", address = "+address+", dob = "+dob+", last_name = "+last_name+", gender = "+gender+", general_command = "+general_command+", activity = "+activity+", mobile_no = "+mobile_no+"]";
}
}
}
Instead of
String h=response.body().toString();
Use
Resul result = response.body();
If condition should be like this
if("1".equals(result.getResponse().getResponse_code())
Use http://www.jsonschema2pojo.org/ to generate pojo class
If you are using gson for parsing the #SerializedName("your_key") ,
#Expose these 2 tags are required. Otherwise those values will be null
This question already has an answer here:
How to convert JSONArray to List with Gson?
(1 answer)
Closed 6 years ago.
How to convert a jsonArray with multiple jsonObjects to an arraylist using Gson.
Here is my Json String:
[{"AccommoAddress":{
"PostalCode":2109,
"Street":"22 Ararat Str",
"Town":"Westdene"
},
"AccommoDetails":{
"AccommoId":0,
"CleaningService":1,
"DSTV":1,
"DedicatedStudyArea":1
},
"AccommoID":1,
"AccommoMainImage":{
"CategoryId":0,
"ContentType":".png",
"DateUploaded":"2016-07-16",
"FileSize":2362,
"ImageCategory":"MAIN",
"ImageId":1,
"ImageName":"images.png"
}]
First , it's not a correct Json format.
"ImageName":"images.png" <- (you need to put a "}" here )
Second , create a entity
public class TargetEntity {
private AccommoAddressEntity AccommoAddress;
private AccommoDetailsEntity AccommoDetails;
private int AccommoID;
private AccommoMainImageEntity AccommoMainImage;
public AccommoAddressEntity getAccommoAddress() {
return AccommoAddress;
}
public void setAccommoAddress(AccommoAddressEntity AccommoAddress) {
this.AccommoAddress = AccommoAddress;
}
public AccommoDetailsEntity getAccommoDetails() {
return AccommoDetails;
}
public void setAccommoDetails(AccommoDetailsEntity AccommoDetails) {
this.AccommoDetails = AccommoDetails;
}
public int getAccommoID() {
return AccommoID;
}
public void setAccommoID(int AccommoID) {
this.AccommoID = AccommoID;
}
public AccommoMainImageEntity getAccommoMainImage() {
return AccommoMainImage;
}
public void setAccommoMainImage(AccommoMainImageEntity AccommoMainImage) {
this.AccommoMainImage = AccommoMainImage;
}
public static class AccommoAddressEntity {
private int PostalCode;
private String Street;
private String Town;
public int getPostalCode() {
return PostalCode;
}
public void setPostalCode(int PostalCode) {
this.PostalCode = PostalCode;
}
public String getStreet() {
return Street;
}
public void setStreet(String Street) {
this.Street = Street;
}
public String getTown() {
return Town;
}
public void setTown(String Town) {
this.Town = Town;
}
}
public static class AccommoDetailsEntity {
private int AccommoId;
private int CleaningService;
private int DSTV;
private int DedicatedStudyArea;
public int getAccommoId() {
return AccommoId;
}
public void setAccommoId(int AccommoId) {
this.AccommoId = AccommoId;
}
public int getCleaningService() {
return CleaningService;
}
public void setCleaningService(int CleaningService) {
this.CleaningService = CleaningService;
}
public int getDSTV() {
return DSTV;
}
public void setDSTV(int DSTV) {
this.DSTV = DSTV;
}
public int getDedicatedStudyArea() {
return DedicatedStudyArea;
}
public void setDedicatedStudyArea(int DedicatedStudyArea) {
this.DedicatedStudyArea = DedicatedStudyArea;
}
}
public static class AccommoMainImageEntity {
private int CategoryId;
private String ContentType;
private String DateUploaded;
private int FileSize;
private String ImageCategory;
private int ImageId;
private String ImageName;
public int getCategoryId() {
return CategoryId;
}
public void setCategoryId(int CategoryId) {
this.CategoryId = CategoryId;
}
public String getContentType() {
return ContentType;
}
public void setContentType(String ContentType) {
this.ContentType = ContentType;
}
public String getDateUploaded() {
return DateUploaded;
}
public void setDateUploaded(String DateUploaded) {
this.DateUploaded = DateUploaded;
}
public int getFileSize() {
return FileSize;
}
public void setFileSize(int FileSize) {
this.FileSize = FileSize;
}
public String getImageCategory() {
return ImageCategory;
}
public void setImageCategory(String ImageCategory) {
this.ImageCategory = ImageCategory;
}
public int getImageId() {
return ImageId;
}
public void setImageId(int ImageId) {
this.ImageId = ImageId;
}
public String getImageName() {
return ImageName;
}
public void setImageName(String ImageName) {
this.ImageName = ImageName;
}
}
}
Third
Gson gson = new Gson();
TargetEntity[] target = gson.fromJson(JsonString,TargetEntity[].class)