I have a problem when I want to retrieve an array from a post response
this is my post
{
"user_email": "xxxx#gmail.com",
"user_password": "12345"
}
and this is my post response , I want get the token value
{
"status": true,
"code": 200,
"message": "Request Succeded: Login success",
"data": [
{
"token": "bsWIVXTLuud2ZbdnUvI8037fT7D0t7MTvusBrNjskah"
}
]
}
this is my model LoginModel.java
#SerializedName("data")
#Expose
private Data data ;
public Data getData() {
return data;
}
public void setData (Data data) {
this.data = data;
}
public LoginModel(String user_email, String user_password) {
this.user_email = user_email;
this.user_password = user_password;
}
Data.java
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
there code I'm tried before ,the text view show nothing
LoginModel loginModelresponse = response.body();
String token = loginModelresponse.getData().getToken();
textView.setText(token);
I want get the token from my post response.
Your data value is an array of tokens, not an object itself
Create a Token class with a token String field, then replace the Data class like so
#SerializedName("data")
#Expose
private List<Token> data ;
To get the token, you must iterate the list
Try to change your LoginModel class, because your response data object is Array type
public class LoginModel {
#SerializedName("status")
#Expose
private Boolean status;
#SerializedName("code")
#Expose
private Integer code;
#SerializedName("message")
#Expose
private String message;
#SerializedName("data")
#Expose
private List<Data> data = null;
public Boolean getStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<Data> getData() {
return data;
}
public void setData(List<Data> data) {
this.data = data;
}
}
use this site to generate a correct response class in java
public class Tokens implements Serializable
{
#SerializedName("token")
#Expose
private String token;
private final static long serialVersionUID = 1577013820593763604L;
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}
// -----------------------------------com.example.Response.java-----------
package com.example;
import java.io.Serializable;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Response implements Serializable
{
#SerializedName("status")
#Expose
private boolean status;
#SerializedName("code")
#Expose
private long code;
#SerializedName("message")
#Expose
private String message;
#SerializedName("data")
#Expose
private List<Tokens> data = null;
private final static long serialVersionUID = -3002290394951662690L;
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public long getCode() {
return code;
}
public void setCode(long code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<Tokens> getData() {
return data;
}
public void setData(List<Tokens> data) {
this.data = data;
}
}
Related
Please Help me
This is my Models
Cases class
public class Cases {
#SerializedName("new")////this key value from json
#Expose
private String _new;
#SerializedName("active")
#Expose
private Integer active;
#SerializedName("critical")
#Expose
private Integer critical;
#SerializedName("recovered")
#Expose
private Integer recovered;
#SerializedName("1M_pop")
#Expose
private String _1MPop;
#SerializedName("total")
#Expose
private Integer total;
public String getNew() {
return _new;
}
public void setNew(String _new) {
this._new = _new;
}
public Integer getActive() {
return active;
}
public void setActive(Integer active) {
this.active = active;
}
public Integer getCritical() {
return critical;
}
public void setCritical(Integer critical) {
this.critical = critical;
}
public Integer getRecovered() {
return recovered;
}
public void setRecovered(Integer recovered) {
this.recovered = recovered;
}
public String get1MPop() {
return _1MPop;
}
public void set1MPop(String _1MPop) {
this._1MPop = _1MPop;
}
public Integer getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
}
Deaths class
public class Deaths {
#SerializedName("new")
#Expose
private String _new;
#SerializedName("1M_pop")
#Expose
private String _1MPop;
#SerializedName("total")
#Expose
private Integer total;
public String getNew() {
return _new;
}
public void setNew(String _new) {
this._new = _new;
}
public String get1MPop() {
return _1MPop;
}
public void set1MPop(String _1MPop) {
this._1MPop = _1MPop;
}
public Integer getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
}
public class Errors {//this is empty class
}
public class Parameters {//this is empty class
}
Tests class
public class Tests {
#SerializedName("1M_pop")
#Expose
private String _1MPop;
#SerializedName("total")
#Expose
private Integer total;
public String get1MPop() {
return _1MPop;
}
public void set1MPop(String _1MPop) {
this._1MPop = _1MPop;
}
public Integer getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
}
Response class
public class Response {
#SerializedName("continent")
#Expose
private String continent;
#SerializedName("country")
#Expose
private String country;
#SerializedName("population")
#Expose
private Integer population;
#SerializedName("cases")
#Expose
private Cases cases;
#SerializedName("deaths")
#Expose
private Deaths deaths;
#SerializedName("tests")
#Expose
private Tests tests;
#SerializedName("day")
#Expose
private String day;
#SerializedName("time")
#Expose
private String time;
public String getContinent() {
return continent;
}
public String getCountry() {
return country;
}
public Integer getPopulation() {
return population;
}
public Cases getCases() {
return cases;
}
public Deaths getDeaths() {
return deaths;
}
public Tests getTests() {
return tests;
}
public String getDay() {
return day;
}
public String getTime() {
return time;
}
}
Covid19Model class
public class Covid19Model {
#SerializedName("get")
#Expose
private String get;
#SerializedName("parameters")
#Expose
private Parameters parameters;
#SerializedName("errors")
#Expose
private Errors errors;
#SerializedName("results")
#Expose
private Integer results;
#SerializedName("response")
#Expose
private List<Response> response;
public String getGet() {
return get;
}
public void setGet(String get) {
this.get = get;
}
public Parameters getParameters() {
return parameters;
}
public void setParameters(Parameters parameters) {
this.parameters = parameters;
}
public Errors getErrors() {
return errors;
}
public void setErrors(Errors errors) {
this.errors = errors;
}
public Integer getResults() {
return results;
}
public void setResults(Integer results) {
this.results = results;
}
public List<Response> getResponse() {
return response;
}
public void setResponse(List<Response> response) {
this.response = response;
}
Covid19WebAPI interface
public interface Covid19WebApi {
#Headers({
"x-rapidapi-host:covid-193.p.rapidapi.com",
"x-rapidapi-key:fb818f40c4msh9ed8e59abf0e867p11b3bfjsn0900d33b78ef"//this is my rapidapi key
})
#GET("statistics")
Call<Covid19Model> getData();
}
MainActivity class
public class MainActivity extends AppCompatActivity {//This is my app MainActivity
List<Response> responses;
private static final String BASE_URL = "https://covid-193.p.rapidapi.com/";//this is covid api website
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create());//this is convert json
Retrofit retrofit = builder.build();
Covid19WebApi covid19WebApi = retrofit.create(Covid19WebApi.class);
Call<Covid19Model> call = covid19WebApi.getData();//this is call api interfacee method
call.enqueue(new Callback<Covid19Model>() {
#Override
public void onResponse(Call<Covid19Model> call, Response<Covid19Model> response) {
responses = response.body().getResponse();
for (Object data:responses){
System.out.println(data);//This my error (expected begin_array but was begin_object )
}
}
#Override
public void onFailure(Call<Covid19Model> call, Throwable t) {
Toast.makeText(MainActivity.this,t.getLocalizedMessage().toString(),Toast.LENGTH_LONG).show();//this is toast message failure
}
});
}
}
What is the problem
My error code ("expected begin_array but was begin_object")
I can't find out what the problem is in these codes and the data doesn't come in response and gives an error instead
As you can see in JSON response, errors and parameters are comes as List.
So please change fields to list in Covid19Model
#SerializedName("parameters")
#Expose
private List<Parameters> parameters;
#SerializedName("errors")
#Expose
private List<Errors> errors;
[
{
"login": "mojombo",
"id": 1,
"node_id": "MDQ6VXNlcjE=",
"avatar_url": "https://avatars0.githubusercontent.com/u/1?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/mojombo",
"html_url": "https://github.com/mojombo",
"followers_url": "https://api.github.com/users/mojombo/followers",
"following_url": "https://api.github.com/users/mojombo/following{/other_user}",
"gists_url": "https://api.github.com/users/mojombo/gists{/gist_id}",
"starred_url": "https://api.github.com/users/mojombo/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/mojombo/subscriptions",
"organizations_url": "https://api.github.com/users/mojombo/orgs",
"repos_url": "https://api.github.com/users/mojombo/repos",
"events_url": "https://api.github.com/users/mojombo/events{/privacy}",
"received_events_url": "https://api.github.com/users/mojombo/received_events",
"type": "User",
"site_admin": false
}
]
Json: https://api.github.com/users
This is URL of an API... how can i parse this object to fetch the data using retrofit?
Here is the example on how to fetch JSON object with array using retrofit. I believe you won't have troubles changing it to work with your data.
Example.java
public class Example {
#SerializedName("PnrNumber")
#Expose
private String pnrNumber;
#SerializedName("Status")
#Expose
private String status;
#SerializedName("ResponseCode")
#Expose
private String responseCode;
#SerializedName("TrainNumber")
#Expose
private String trainNumber;
#SerializedName("TrainName")
#Expose
private String trainName;
#SerializedName("JourneyClass")
#Expose
private String journeyClass;
#SerializedName("ChatPrepared")
#Expose
private String chatPrepared;
#SerializedName("From")
#Expose
private String from;
#SerializedName("To")
#Expose
private String to;
#SerializedName("JourneyDate")
#Expose
private String journeyDate;
#SerializedName("Passangers")
#Expose
private List<Passanger> passangers = null;
public String getPnrNumber() {
return pnrNumber;
}
public void setPnrNumber(String pnrNumber) {
this.pnrNumber = pnrNumber;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getResponseCode() {
return responseCode;
}
public void setResponseCode(String responseCode) {
this.responseCode = responseCode;
}
public String getTrainNumber() {
return trainNumber;
}
public void setTrainNumber(String trainNumber) {
this.trainNumber = trainNumber;
}
public String getTrainName() {
return trainName;
}
public void setTrainName(String trainName) {
this.trainName = trainName;
}
public String getJourneyClass() {
return journeyClass;
}
public void setJourneyClass(String journeyClass) {
this.journeyClass = journeyClass;
}
public String getChatPrepared() {
return chatPrepared;
}
public void setChatPrepared(String chatPrepared) {
this.chatPrepared = chatPrepared;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public String getJourneyDate() {
return journeyDate;
}
public void setJourneyDate(String journeyDate) {
this.journeyDate = journeyDate;
}
public List<Passanger> getPassangers() {
return passangers;
}
public void setPassangers(List<Passanger> passangers) {
this.passangers = passangers;
}
}
Passanger.Java
public class Passanger {
#SerializedName("Passenger")
#Expose
private String passenger;
#SerializedName("BookingStatus")
#Expose
private String bookingStatus;
#SerializedName("CurrentStatus")
#Expose
private String currentStatus;
public String getPassenger() {
return passenger;
}
public void setPassenger(String passenger) {
this.passenger = passenger;
}
public String getBookingStatus() {
return bookingStatus;
}
public void setBookingStatus(String bookingStatus) {
this.bookingStatus = bookingStatus;
}
public String getCurrentStatus() {
return currentStatus;
}
public void setCurrentStatus(String currentStatus) {
this.currentStatus = currentStatus;
}
}
Here are the classes which are generated from the Response which you have provided in the question.
You can use this link to generate the POJO class for JSON response.
JSON TO POJO
Add this gradle:
implementation 'com.google.code.gson:gson:2.8.2'
Init the Gson buildr:
private Gson gson;
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("M/d/yy hh:mm a");
gson = gsonBuilder.create();
Parse the JSON using GSON
gson.fromJson(jsonObject.getJSONObject("data").toString(), Example.class);
These are the basic steps to parse the JSON using GSON.
For more information you can refer to the below article:
Parsing JSON on Android using GSON
Or Check the GSON official GitHub Repository
GSON
I checked the following json, it is valid, But http://www.jsonschema2pojo.org/ is not converting it into POJO object so I can fetch values from it, I need "nameValuePairs" object in following model. Please help. Thanks in advance
[
"order-chat-1",
{
"nameValuePairs":{
"chat":{
"nameValuePairs":{
"id":19,
"order_id":6,
"sender_id":10,
"receiver_id":3,
"message":"Hi",
"is_read":0,
"created_at":"2018-10-19 16:23:28",
"updated_at":"2018-10-19 16:23:28",
"is_sender":false
}
},
"message":"Hello from chef",
"message_type":"Message",
"is_sender":false
}
}
]
Here is the code to put on http://www.jsonschema2pojo.org/
{
"type":"object",
"properties":{
"chat":{
"type":"object",
"properties":{
"nameValuePairs":{
"type":"object",
"properties":{
"id": {"type": "integer"},
"order_id":{"type": "integer"},
"sender_id":{"type": "integer"},
"receiver_id":{"type": "integer"},
"message":{"type": "string"},
"is_read":{"type": "integer"},
"created_at":{"type": "string"},
"updated_at":{"type": "string"},
"is_sender":{"type": "boolean"}
}
}
}
},
"message":{"type": "string"},
"message_type":{"type": "string"},
"is_sender":{"type": "boolean"}
}
}
That produces the following POJO's where Example.class is your root object, change the name as you want.
-----------------------------------com.example.Chat.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Chat {
#SerializedName("nameValuePairs")
#Expose
private NameValuePairs nameValuePairs;
public NameValuePairs getNameValuePairs() {
return nameValuePairs;
}
public void setNameValuePairs(NameValuePairs nameValuePairs) {
this.nameValuePairs = nameValuePairs;
}
public Chat withNameValuePairs(NameValuePairs nameValuePairs) {
this.nameValuePairs = nameValuePairs;
return this;
}
}
-----------------------------------com.example.Example.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("chat")
#Expose
private Chat chat;
#SerializedName("message")
#Expose
private String message;
#SerializedName("message_type")
#Expose
private String messageType;
#SerializedName("is_sender")
#Expose
private boolean isSender;
public Chat getChat() {
return chat;
}
public void setChat(Chat chat) {
this.chat = chat;
}
public Example withChat(Chat chat) {
this.chat = chat;
return this;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Example withMessage(String message) {
this.message = message;
return this;
}
public String getMessageType() {
return messageType;
}
public void setMessageType(String messageType) {
this.messageType = messageType;
}
public Example withMessageType(String messageType) {
this.messageType = messageType;
return this;
}
public boolean isIsSender() {
return isSender;
}
public void setIsSender(boolean isSender) {
this.isSender = isSender;
}
public Example withIsSender(boolean isSender) {
this.isSender = isSender;
return this;
}
}
-----------------------------------com.example.NameValuePairs.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class NameValuePairs {
#SerializedName("id")
#Expose
private int id;
#SerializedName("order_id")
#Expose
private int orderId;
#SerializedName("sender_id")
#Expose
private int senderId;
#SerializedName("receiver_id")
#Expose
private int receiverId;
#SerializedName("message")
#Expose
private String message;
#SerializedName("is_read")
#Expose
private int isRead;
#SerializedName("created_at")
#Expose
private String createdAt;
#SerializedName("updated_at")
#Expose
private String updatedAt;
#SerializedName("is_sender")
#Expose
private boolean isSender;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public NameValuePairs withId(int id) {
this.id = id;
return this;
}
public int getOrderId() {
return orderId;
}
public void setOrderId(int orderId) {
this.orderId = orderId;
}
public NameValuePairs withOrderId(int orderId) {
this.orderId = orderId;
return this;
}
public int getSenderId() {
return senderId;
}
public void setSenderId(int senderId) {
this.senderId = senderId;
}
public NameValuePairs withSenderId(int senderId) {
this.senderId = senderId;
return this;
}
public int getReceiverId() {
return receiverId;
}
public void setReceiverId(int receiverId) {
this.receiverId = receiverId;
}
public NameValuePairs withReceiverId(int receiverId) {
this.receiverId = receiverId;
return this;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public NameValuePairs withMessage(String message) {
this.message = message;
return this;
}
public int getIsRead() {
return isRead;
}
public void setIsRead(int isRead) {
this.isRead = isRead;
}
public NameValuePairs withIsRead(int isRead) {
this.isRead = isRead;
return this;
}
public String getCreatedAt() {
return createdAt;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
public NameValuePairs withCreatedAt(String createdAt) {
this.createdAt = createdAt;
return this;
}
public String getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(String updatedAt) {
this.updatedAt = updatedAt;
}
public NameValuePairs withUpdatedAt(String updatedAt) {
this.updatedAt = updatedAt;
return this;
}
public boolean isIsSender() {
return isSender;
}
public void setIsSender(boolean isSender) {
this.isSender = isSender;
}
public NameValuePairs withIsSender(boolean isSender) {
this.isSender = isSender;
return this;
}
}
It is valid from JavaScript prospective, but not form standard Java libraries such as GSON, Jackson or whatever www.jsonschema2pojo.org uses.
There are two things:
It is an Array on top
There are two different types in that array String and an Object
It can be converted only to Object[] or Collection<Object> (e.g.List, Set etc).
But to do that you have to have a custom Serializer/Deserializer.
I worked with another technique to resolve this, I converted this Object to String through Gson() and after that with subString method I removed the first 16 characters and the last character of the newly created string, then I Converted that String to POJO Object.
This question already has answers here:
Why does Gson fromJson throw a JsonSyntaxException: Expected BEGIN_OBJECT but was BEGIN_ARRAY?
(2 answers)
Closed 4 years ago.
I get the following json response from my api in my android application, i am using Gson deserialization to parse my data and populate my listview.
API Response:
{
"message":"success",
"success":"1",
"sessionKey":"a422e60213322845b85ae122de53269f",
"data":"[{\"system_id\":1,\"logo_url\":\"https:\\\/\\\/www.beta.system.com\\\/api\\\/icons\\\/3244ffjg.jpg\",\"organization_name\":\"Test Organasation\"}]"
}
My Class:
public class SystemResponse {
#Expose
#SerializedName("message")
private String message;
#Expose
#SerializedName("success")
private String statusCode;
#Expose
#SerializedName("sessionKey")
private String sessionKey;
#Expose
#SerializedName("data")
private List<System> data;
public String getStatusCode() {
return statusCode;
}
public void setStatusCode(String statusCode) {
this.statusCode = statusCode;
}
public String getSessionKey() {
return sessionKey;
}
public void setSessionKey(String sessionKey) {
this.sessionKey = sessionKey;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<System> getSystems() {
return data;
}
public void setSystems(List<System> data) {
this.data = data;
}
public static class System{
#Expose
#SerializedName("system_id")
private Long systemId;
#Expose
#SerializedName("logo_url")
private String logoUrl;
#Expose
#SerializedName("organization_name")
private String organizationName;
public Long getSystemId() {
return systemId;
}
public void setSystemId(Long systemId) {
this.systemId = systemId;
}
public String getLogoUrl() {
return logoUrl;
}
public void setLogoUrl(String logoUrl) {
this.logoUrl = logoUrl;
}
public String getOrganizationName() {
return organizationName;
}
public void setOrganizationName(String organizationName) {
this.organizationName = organizationName;
}
}
}
Api Request service, omitted the other code:
public Observable<SystemResponse> doServerAccountRequestApiCall(String param) {
return Rx2AndroidNetworking.get(ApiEndPoint.ENDPOINT_GET_ACCOUNTS)
.build()
.getObjectObservable(SystemResponse.class);
}
Request api call in my controller class, omitted the other code.
getCompositeDisposable().add(getDataManager() .doServerAccountRequestApiCall(params))
.subscribeOn(getSchedulerProvider().io())
.observeOn(getSchedulerProvider().ui())
.subscribe(new Consumer<SystemResponse>() {
#Override
public void accept(#NonNull SystemResponse response)
throws Exception {
//error here
}
}, new Consumer<Throwable>() {}));
I am getting getting this error:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 92 path $.data
data parameter value is starting with " So it is a String not an array.
Use http://www.jsonschema2pojo.org/ to generate a model class.
Try this model class :
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("message")
#Expose
private String message;
#SerializedName("success")
#Expose
private String success;
#SerializedName("sessionKey")
#Expose
private String sessionKey;
#SerializedName("data")
#Expose
private String data;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getSuccess() {
return success;
}
public void setSuccess(String success) {
this.success = success;
}
public String getSessionKey() {
return sessionKey;
}
public void setSessionKey(String sessionKey) {
this.sessionKey = sessionKey;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
}
I am trying to convert the response from server which is a JSON string,I want to convert that JSONstring to java object.I am trying Gson.Please someone explain and tell me the steps how to do it using Gson.
#Override
public void onClick(View v) {
if (v == mLoginButton) {
LoginUser();
}
if (v==mSignUpBtn){
Intent intent=new Intent(LoginActivity.this,RegistrationActivity.class);
startActivity(intent);
}
}
private void LoginUser() {
// final String username = editTextUsername.getText().toString().trim();
final String password = editTextPassword.getText().toString().trim();
final String email = editTextEmail.getText().toString().trim();
StringRequest postStringRequest = new StringRequest(Request.Method.POST,LOGIN_API,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(LoginActivity.this, response, Toast.LENGTH_LONG).show();
Log.d(TAG,"Reponse Check :"+response);
// Gson gson = new Gson();
// String jsonInString = "{}";
//LoginActivity staff = gson.fromJson(jsonInString, LoginActivity.class);
//Log.d(TAG,"Reponse Check staff :"+staff);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(LoginActivity.this, error.toString(), Toast.LENGTH_LONG).show();
Log.e(TAG,"Error Response Check :"+error);
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
Log.d(TAG,"For email :"+email);
Log.d(TAG,"For password :"+password);
//try {
Log.d(TAG,"My Credentials email URL Encoder: "+( mEncryption.AESEncode(email)));
Log.d(TAG,"My Credentials email URL DECODED: "+( mEncryption.AESDecode(mEncryption.AESEncode(email))));
params.put("data[User][email]",(mEncryption.AESEncode(email)));
Log.d(TAG,"My Credentials pass URL Encoder: "+( mEncryption.AESEncode(password)));
paa
}
logcat
03-16 16:36:08.346 2618-3428/com.example.user.myapplication D/Null: For email :abc#gmail.com
03-16 16:36:08.346 2618-3428/com.example.user.myapplication D/Null: For password :12345678
03-16 16:36:08.354 2618-3428/com.example.user.myapplication D/Null: My Credentials email URL Encoder: RyUMRBg7UyeIlFBBtNemZFuG46PJtAIdiZWXnlJ4zNI=
03-16 16:36:08.358 2618-3428/com.example.user.myapplication D/Null: My Credentials email URL DECODED: abc#gmail.com
03-16 16:36:08.360 2618-3428/com.example.user.myapplication D/Null: My Credentials pass URL Encoder: pfrt1fKLkoZhAT6hoMJFiA==
03-16 16:36:08.361 2618-3428/com.example.user.myapplication D/Null: Params :{data[User][password]=pfrt1fKLkoZhAT6hoMJFiA==
, data[User][email]=RyUMRBg7UyeIlFBBtNemZFuG46PJtAIdiZWXnlJ4zNI=
}
03-16 16:36:08.505 2618-2618/com.example.user.myapplication D/Null: Reponse Check :{"code":200,"user":{"User":{"id":"ui1bJkK19jxbaquTboA2oQ==","email":"RyUMRBg7UyeIlFBBtNemZFuG46PJtAIdiZWXnlJ4zNI=","status":"1","verified":"1","created":"2016-03-07 11:41:59","modified":"2016-04-07 15:43:43","token":"6b987332b77d7c69d76bf7be80a85177fb7fa08d"},"Profile":{"id":"1","first_name":"abc","last_name":"fgh","bio":"sfafaf","address":"82, Debinibash Road\r\nDum Dum, P.O. - Motijheel","phone":"+913325505055","profile_pic":"\/img\/356a192b7913b04c54574d18c28d46e6395428ab\/license.jpg","user_id":"1","Contributor":{"id":"31","profile_id":"1","status":"1","vs_cdn_id":"261961777","secret_token":"s-7Va5z","uploaded_on":null,"statement":"AOK KJDHKJDH bkgkg kkhkjh kjhkj kjh kjhkjh","time":"7 hours per month","created":"2016-05-02 18:40:11","modified":"2016-05-02 18:41:29"},"Moderator":[]},"redirect":"\/"}}
You can use in a generic way like:
private final static Gson GSON = new GsonBuilder().create();
public static <T> T fromJSON(String json, Class<T> clazz) {
try {
return GSON.fromJson(json, clazz);
} catch (JsonSyntaxException e) {
LOGGER.warn("Could not deserialize object", e);
}
return null;
}
You can't make activity/fragment from json.
In your onResponse() method:
ModelObject obj = new Gson().fromJson(jsonString, ModelObject.class);
And make ModelObject class something like this:
public class ModelObject {
int field1;
int field2;
//here you should make getters and setters;
}
After it you can do anything you need with this object (pass it to any activity or fragment).
Gson will map the values to the corresponding model class object if the fields are given correctly. Have a look at the below model classes. After that, if you call Example data = GSON.fromJson(yourJson, Example.class); , this data object will have all that you need.
-----------------------------------com.example.Contributor.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Contributor {
#SerializedName("id")
#Expose
private String id;
#SerializedName("profile_id")
#Expose
private String profileId;
#SerializedName("status")
#Expose
private String status;
#SerializedName("vs_cdn_id")
#Expose
private String vsCdnId;
#SerializedName("secret_token")
#Expose
private String secretToken;
#SerializedName("uploaded_on")
#Expose
private Object uploadedOn;
#SerializedName("statement")
#Expose
private String statement;
#SerializedName("time")
#Expose
private String time;
#SerializedName("created")
#Expose
private String created;
#SerializedName("modified")
#Expose
private String modified;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getProfileId() {
return profileId;
}
public void setProfileId(String profileId) {
this.profileId = profileId;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getVsCdnId() {
return vsCdnId;
}
public void setVsCdnId(String vsCdnId) {
this.vsCdnId = vsCdnId;
}
public String getSecretToken() {
return secretToken;
}
public void setSecretToken(String secretToken) {
this.secretToken = secretToken;
}
public Object getUploadedOn() {
return uploadedOn;
}
public void setUploadedOn(Object uploadedOn) {
this.uploadedOn = uploadedOn;
}
public String getStatement() {
return statement;
}
public void setStatement(String statement) {
this.statement = statement;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getCreated() {
return created;
}
public void setCreated(String created) {
this.created = created;
}
public String getModified() {
return modified;
}
public void setModified(String modified) {
this.modified = modified;
}
}
-----------------------------------com.example.Example.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("code")
#Expose
private Integer code;
#SerializedName("user")
#Expose
private User user;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
-----------------------------------com.example.Profile.java-----------------------------------
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Profile {
#SerializedName("id")
#Expose
private String id;
#SerializedName("first_name")
#Expose
private String firstName;
#SerializedName("last_name")
#Expose
private String lastName;
#SerializedName("bio")
#Expose
private String bio;
#SerializedName("address")
#Expose
private String address;
#SerializedName("phone")
#Expose
private String phone;
#SerializedName("profile_pic")
#Expose
private String profilePic;
#SerializedName("user_id")
#Expose
private String userId;
#SerializedName("Contributor")
#Expose
private Contributor contributor;
#SerializedName("Moderator")
#Expose
private List<Object> moderator = null;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getBio() {
return bio;
}
public void setBio(String bio) {
this.bio = bio;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getProfilePic() {
return profilePic;
}
public void setProfilePic(String profilePic) {
this.profilePic = profilePic;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public Contributor getContributor() {
return contributor;
}
public void setContributor(Contributor contributor) {
this.contributor = contributor;
}
public List<Object> getModerator() {
return moderator;
}
public void setModerator(List<Object> moderator) {
this.moderator = moderator;
}
}
-----------------------------------com.example.User.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class User {
#SerializedName("User")
#Expose
private User_ user;
#SerializedName("Profile")
#Expose
private Profile profile;
#SerializedName("redirect")
#Expose
private String redirect;
public User_ getUser() {
return user;
}
public void setUser(User_ user) {
this.user = user;
}
public Profile getProfile() {
return profile;
}
public void setProfile(Profile profile) {
this.profile = profile;
}
public String getRedirect() {
return redirect;
}
public void setRedirect(String redirect) {
this.redirect = redirect;
}
}
-----------------------------------com.example.User_.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class User_ {
#SerializedName("id")
#Expose
private String id;
#SerializedName("email")
#Expose
private String email;
#SerializedName("status")
#Expose
private String status;
#SerializedName("verified")
#Expose
private String verified;
#SerializedName("created")
#Expose
private String created;
#SerializedName("modified")
#Expose
private String modified;
#SerializedName("token")
#Expose
private String token;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getVerified() {
return verified;
}
public void setVerified(String verified) {
this.verified = verified;
}
public String getCreated() {
return created;
}
public void setCreated(String created) {
this.created = created;
}
public String getModified() {
return modified;
}
public void setModified(String modified) {
this.modified = modified;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}