How can i convert json string to java object in android? - java

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;
}
}

Related

How to Fetch data from API using Retrofit in Android

I'm Trying to call API using retrofit in Android. Although I'm successfully able to api in response I'm getting Success Code = 200. But Apart from that Inside Json object Json array is null although while I'm trying to call same api in Postman I'm getting the desire result.
I'm trying to call using POST request
URL Request :- https://example.com/AD1/api/user/profile
I'm passing parameter in Body userid:- MFL176116
Below Postman
APIInterface.java
public interface APIInterface {
#POST("profile")
Call<ProfilePojo> getUserProfile(#Body ProfilePojo profilePojo);
}
ProfilePojo.java
public class ProfilePojo {
#SerializedName("message")
#Expose
private String message;
#SerializedName("code")
#Expose
private Integer code;
#SerializedName("user_data")
#Expose
private List<UserDatum> userData = new ArrayList();
private String userid;
public ProfilePojo(String userid) {
this.userid = userid;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<UserDatum> getUserData() {
return userData;
}
public void setUserData(List<UserDatum> userData) {
this.userData = userData;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public class UserDatum {
#SerializedName("id")
#Expose
private String id;
#SerializedName("username")
#Expose
private String username;
#SerializedName("password")
#Expose
private String password;
#SerializedName("under_id")
#Expose
private String underId;
#SerializedName("place_under_id")
#Expose
private String placeUnderId;
#SerializedName("mobile")
#Expose
private String mobile;
#SerializedName("side")
#Expose
private String side;
#SerializedName("email")
#Expose
private String email;
#SerializedName("status")
#Expose
private String status;
#SerializedName("member_name")
#Expose
private String memberName;
#SerializedName("package_id")
#Expose
private String packageId;
#SerializedName("package_id1")
#Expose
private String packageId1;
#SerializedName("avatar")
#Expose
private String avatar;
#SerializedName("gender")
#Expose
private Object gender;
#SerializedName("date_of_birth")
#Expose
private Object dateOfBirth;
#SerializedName("address_line1")
#Expose
private String addressLine1;
#SerializedName("address_line2")
#Expose
private String addressLine2;
#SerializedName("country")
#Expose
private String country;
#SerializedName("country_code")
#Expose
private String countryCode;
#SerializedName("state")
#Expose
private String state;
#SerializedName("city")
#Expose
private String city;
#SerializedName("pincode")
#Expose
private String pincode;
#SerializedName("pancard_no")
#Expose
private String pancardNo;
#SerializedName("adharcard_no")
#Expose
private String adharcardNo;
#SerializedName("franchaise_type")
#Expose
private String franchaiseType;
#SerializedName("franchise_id")
#Expose
private Object franchiseId;
#SerializedName("franchise_per")
#Expose
private Object franchisePer;
#SerializedName("franchise_status")
#Expose
private Object franchiseStatus;
#SerializedName("transaction_pass")
#Expose
private String transactionPass;
#SerializedName("id_proof")
#Expose
private Object idProof;
#SerializedName("address_proof")
#Expose
private Object addressProof;
#SerializedName("self_video")
#Expose
private String selfVideo;
#SerializedName("residential_proof")
#Expose
private String residentialProof;
#SerializedName("btc_address")
#Expose
private Object btcAddress;
#SerializedName("perfect_money")
#Expose
private Object perfectMoney;
#SerializedName("email_status")
#Expose
private String emailStatus;
#SerializedName("email_verify")
#Expose
private String emailVerify;
#SerializedName("created_on")
#Expose
private String createdOn;
#SerializedName("edited_on")
#Expose
private String editedOn;
#SerializedName("isDeleted")
#Expose
private String isDeleted;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUnderId() {
return underId;
}
public void setUnderId(String underId) {
this.underId = underId;
}
public String getPlaceUnderId() {
return placeUnderId;
}
public void setPlaceUnderId(String placeUnderId) {
this.placeUnderId = placeUnderId;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getSide() {
return side;
}
public void setSide(String side) {
this.side = side;
}
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 getMemberName() {
return memberName;
}
public void setMemberName(String memberName) {
this.memberName = memberName;
}
public String getPackageId() {
return packageId;
}
public void setPackageId(String packageId) {
this.packageId = packageId;
}
public String getPackageId1() {
return packageId1;
}
public void setPackageId1(String packageId1) {
this.packageId1 = packageId1;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public Object getGender() {
return gender;
}
public void setGender(Object gender) {
this.gender = gender;
}
public Object getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Object dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getAddressLine1() {
return addressLine1;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
public String getAddressLine2() {
return addressLine2;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getCountryCode() {
return countryCode;
}
public void setCountryCode(String countryCode) {
this.countryCode = countryCode;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getPincode() {
return pincode;
}
public void setPincode(String pincode) {
this.pincode = pincode;
}
public String getPancardNo() {
return pancardNo;
}
public void setPancardNo(String pancardNo) {
this.pancardNo = pancardNo;
}
public String getAdharcardNo() {
return adharcardNo;
}
public void setAdharcardNo(String adharcardNo) {
this.adharcardNo = adharcardNo;
}
public String getFranchaiseType() {
return franchaiseType;
}
public void setFranchaiseType(String franchaiseType) {
this.franchaiseType = franchaiseType;
}
public Object getFranchiseId() {
return franchiseId;
}
public void setFranchiseId(Object franchiseId) {
this.franchiseId = franchiseId;
}
public Object getFranchisePer() {
return franchisePer;
}
public void setFranchisePer(Object franchisePer) {
this.franchisePer = franchisePer;
}
public Object getFranchiseStatus() {
return franchiseStatus;
}
public void setFranchiseStatus(Object franchiseStatus) {
this.franchiseStatus = franchiseStatus;
}
public String getTransactionPass() {
return transactionPass;
}
public void setTransactionPass(String transactionPass) {
this.transactionPass = transactionPass;
}
public Object getIdProof() {
return idProof;
}
public void setIdProof(Object idProof) {
this.idProof = idProof;
}
public Object getAddressProof() {
return addressProof;
}
public void setAddressProof(Object addressProof) {
this.addressProof = addressProof;
}
public String getSelfVideo() {
return selfVideo;
}
public void setSelfVideo(String selfVideo) {
this.selfVideo = selfVideo;
}
public String getResidentialProof() {
return residentialProof;
}
public void setResidentialProof(String residentialProof) {
this.residentialProof = residentialProof;
}
public Object getBtcAddress() {
return btcAddress;
}
public void setBtcAddress(Object btcAddress) {
this.btcAddress = btcAddress;
}
public Object getPerfectMoney() {
return perfectMoney;
}
public void setPerfectMoney(Object perfectMoney) {
this.perfectMoney = perfectMoney;
}
public String getEmailStatus() {
return emailStatus;
}
public void setEmailStatus(String emailStatus) {
this.emailStatus = emailStatus;
}
public String getEmailVerify() {
return emailVerify;
}
public void setEmailVerify(String emailVerify) {
this.emailVerify = emailVerify;
}
public String getCreatedOn() {
return createdOn;
}
public void setCreatedOn(String createdOn) {
this.createdOn = createdOn;
}
public String getEditedOn() {
return editedOn;
}
public void setEditedOn(String editedOn) {
this.editedOn = editedOn;
}
public String getIsDeleted() {
return isDeleted;
}
public void setIsDeleted(String isDeleted) {
this.isDeleted = isDeleted;
}
}
}
Dashboard.java
private void getUserProfile() {
apiInterface = ApiLinks.getClient().create(APIInterface.class);
ProfilePojo profilePojo = new ProfilePojo("MFL176116");
Call<ProfilePojo> call = apiInterface.getUserProfile(profilePojo);
call.enqueue(new Callback<ProfilePojo>() {
#Override
public void onResponse(#NonNull Call<ProfilePojo> call, #NonNull Response<ProfilePojo> response) {
ProfilePojo profilePojo = response.body();
Toast.makeText(getApplicationContext(), "sucess", Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(#NonNull Call<ProfilePojo> call, #NonNull Throwable t) {
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
After debugging the code can see Message is success, code =200, but userdata size ==0 please help me to get rid of this error
Check again the way that you are calling the api, even your userid is getting null, probably it's getting null in the user, but the response is 200 bc there was no error, simply no user with that id.

Only one HTTP method is allowed. Found GET and PUT

java.lang.IllegalArgumentException: Only one HTTP method is allowed. Found: GET and PUT.
for method ApiInterface.UpdateCoordinates
i have tried for the last 2 hours to update the coordinates but it ain't working keeps throwing this error
java.lang.IllegalArgumentException: Only one HTTP method is allowed. Found: GET and PUT.
for method ApiInterface.UpdateCoordinates
at retrofit2.Utils.methodError(Utils.java:52)
at retrofit2.Utils.methodError(Utils.java:42)
at retrofit2.RequestFactory$Builder.parseHttpMethodAndPath(RequestFactory.java:251)
at retrofit2.RequestFactory$Builder.parseMethodAnnotation(RequestFactory.java:224)
at retrofit2.RequestFactory$Builder.build(RequestFactory.java:171)
at retrofit2.RequestFactory.parseAnnotations(RequestFactory.java:67)
at retrofit2.ServiceMethod.parseAnnotations(ServiceMethod.java:26)
at retrofit2.Retrofit.loadServiceMethod(Retrofit.java:170)
at retrofit2.Retrofit$1.invoke(Retrofit.java:149)
at java.lang.reflect.Proxy.invoke(Proxy.java:1006)
at $Proxy0.UpdateCoordinates(Unknown Source)
at com.example.charlo.jkuat_mobile_app.util.LocationService$1.onLocationResult(LocationService.java:54)
Model classes
the update model class
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class GpsUpdate {
#SerializedName("success")
#Expose
private Boolean success;
#SerializedName("data")
#Expose
private Data data;
#SerializedName("message")
#Expose
private String message;
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
model class
the data model class
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Data {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("driverid")
#Expose
private Integer driverid;
#SerializedName("companyid")
#Expose
private Integer companyid;
#SerializedName("vehicleid")
#Expose
private Integer vehicleid;
#SerializedName("warehouseid")
#Expose
private Integer warehouseid;
#SerializedName("orders")
#Expose
private Integer orders;
#SerializedName("status")
#Expose
private Integer status;
#SerializedName("latitute")
#Expose
private String latitute;
#SerializedName("longitude")
#Expose
private String longitude;
#SerializedName("tripdate")
#Expose
private String tripdate;
#SerializedName("created_at")
#Expose
private String createdAt;
#SerializedName("updated_at")
#Expose
private String updatedAt;
public Data(String latitute, String longitude) {
this.latitute = latitute;
this.longitude = longitude;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getDriverid() {
return driverid;
}
public void setDriverid(Integer driverid) {
this.driverid = driverid;
}
public Integer getCompanyid() {
return companyid;
}
public void setCompanyid(Integer companyid) {
this.companyid = companyid;
}
public Integer getVehicleid() {
return vehicleid;
}
public void setVehicleid(Integer vehicleid) {
this.vehicleid = vehicleid;
}
public Integer getWarehouseid() {
return warehouseid;
}
public void setWarehouseid(Integer warehouseid) {
this.warehouseid = warehouseid;
}
public Integer getOrders() {
return orders;
}
public void setOrders(Integer orders) {
this.orders = orders;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getLatitute() {
return latitute;
}
public void setLatitute(String latitute) {
this.latitute = latitute;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getTripdate() {
return tripdate;
}
public void setTripdate(String tripdate) {
this.tripdate = tripdate;
}
public String getCreatedAt() {
return createdAt;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
public String getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(String updatedAt) {
this.updatedAt = updatedAt;
}
}
Interface
interface class
#PUT("update_driver/{dispatchid}?")
Call<GpsUpdate> UpdateCoordinates(#Path("dispatchid") int id, #Field("latitude") String latitude, #Field("longitude") String longitude );
location service class
the update class which sends the coordinates to the backend
#Override
public void onCreate() {
super.onCreate();
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
tokenManager = TokenManager.getInstance(getSharedPreferences("prefs", MODE_PRIVATE));
service = ApiClient.createService(ApiInterface.class);
locationCallback = new LocationCallback(){
#Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
double lat = locationResult.getLastLocation().getLatitude();
double lng = locationResult.getLastLocation().getLongitude();
String latitude = String.valueOf(lat);
String longitude = String.valueOf(lng);
Data data = new Data(latitude,longitude);
Call<GpsUpdate> call = service.UpdateCoordinates(tokenManager.getToken().getDispatchid(),data.getLatitute(), data.getLongitude());
call.enqueue(new Callback<GpsUpdate>() {
#Override
public void onResponse(Call<GpsUpdate> call, Response<GpsUpdate> response) {
}
#Override
public void onFailure(Call<GpsUpdate> call, Throwable t) {
}
});
I think I should have marked this as a duplicate:
Retrofit: how fix "only one http method is allowed. found: get and get"?
Try changing the
#Path("dispatchid") int id
to
#Path("dispatchid") int dispatchid

Retrofit post request null body

I'm trying to post my data in json format. I think I'm doing it right, but it's making the mistake:
body = null, response code =417
Json data needs to post in the following format:
{
"Users": [{
'Phone': 'xxxxxxxxxxx',
'Name': 'yyyyy'
}
]
}
My code is all:
#POST("api")
#FormUrlEncoded
Call<TRList> savePost(#Field("Phone") String Phone,
#Field("Name") String Name);
}
}
public class UsersList {
#SerializedName("Users")
#Expose
private List<Post> users = null;
public List<Post> getUsers() {
return users;
}
public void setTr(List<Post> users) {
this.users = users;
}
}
public class Post {
#SerializedName("Phone")
#Expose
private String phone;
#SerializedName("AS")
#Expose
private String Name;
//getter and setter methods
}
public void sendPost(Post post){
mAPIService.savePost(post.getPhone().toString(),post.getName().toString()).enqueue(new Callback<UsersList>() {
#Override
public void onResponse(Call<UsersList> call, Response<UsersList> response) {
Log.d("requestError", "onResponse: "+ call.request().body().toString());
if(response.isSuccessful()) {
showResponse(response.body().toString());
}
}
Please check below code
First create Output class
Create class User
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class User {
#SerializedName("Phone")
#Expose
private String phone;
#SerializedName("Name")
#Expose
private String name;
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Create class UserList
public class UserList {
#SerializedName("Users")
#Expose
private List<User> users = null;
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
}
for input class you already have post class
public class Post {
#SerializedName("Phone")
#Expose
private String phone;
#SerializedName("AS")
#Expose
private String Name;
//getter and setter methods
}
on your interface create this method
#POST("api")
Call<UserList> savePost(##Body Post post);
call service
public void sendPost(Post post){
mAPIService.savePost(post).enqueue(new Callback<UserList>() {
#Override
public void onResponse(Call<UserList> call, Response<UserList> response) {
Log.d("requestError", "onResponse: "+ call.request().body().toString());
if(response.isSuccessful()) {
showResponse(response.body().toString());
}
}

How to add array list to rest API request using Rest Assured?

I'm using rest assured for Rest api testing with the help of POJO classes like getter and setter methods to set the values but i'm stuck with array list in between rest request,please any one provide proper code to get exact below request to post using rest assured.
Request:
{
"firstName":"SuryaNAMASKARAM",
"lastName":"mangalam",
"mobileNo" :4954758490,
"emailId" :"surya.mangalam#futureretail.in",
"houseNoStreet":"123456",
"buildingName":"",
"landmark":"Nirmala jathara",
"paymentDetail" :
[{"paymentType":"CASH","No":"3519000012","Date":"16-06-2018","amount":"100.00"}]
}
CustomerCreate Class:
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("firstName")
#Expose
private String firstName;
#SerializedName("lastName")
#Expose
private String lastName;
#SerializedName("mobileNo")
#Expose
private Integer mobileNo;
#SerializedName("emailId")
#Expose
private String emailId;
#SerializedName("houseNoStreet")
#Expose
private String houseNoStreet;
#SerializedName("buildingName")
#Expose
private String buildingName;
#SerializedName("landmark")
#Expose
private String landmark;
#SerializedName("paymentDetail")
#Expose
private List<PaymentDetail> paymentDetail = null;
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 Integer getMobileNo() {
return mobileNo;
}
public void setMobileNo(Integer mobileNo) {
this.mobileNo = mobileNo;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public String getHouseNoStreet() {
return houseNoStreet;
}
public void setHouseNoStreet(String houseNoStreet) {
this.houseNoStreet = houseNoStreet;
}
public String getBuildingName() {
return buildingName;
}
public void setBuildingName(String buildingName) {
this.buildingName = buildingName;
}
public String getLandmark() {
return landmark;
}
public void setLandmark(String landmark) {
this.landmark = landmark;
}
public List<PaymentDetail> getPaymentDetail() {
return paymentDetail;
}
public void setPaymentDetail(List<PaymentDetail> paymentDetail) {
this.paymentDetail = paymentDetail;
}
}
PaymentDetails:
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class PaymentDetail {
#SerializedName("paymentType")
#Expose
private String paymentType;
#SerializedName("No")
#Expose
private String no;
#SerializedName("Date")
#Expose
private String date;
#SerializedName("amount")
#Expose
private String amount;
public String getPaymentType() {
return paymentType;
}
public void setPaymentType(String paymentType) {
this.paymentType = paymentType;
}
public String getNo() {
return no;
}
public void setNo(String no) {
this.no = no;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
}
Test Class:
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.test.requestpojo.Example;
import com.test.requestpojo.PaymentDetail;
public class TestAPI {
public void setTestData() throws JSONException {
Example example = new Example();
example.setFirstName("Rajesh");
example.setLastName("Kuchana");
example.setMobileNo("3434343434");
example.setEmailId("rajesh.kuchana#futureretail.in");
example.setDateOfBirth("10-10-2018");
example.setGender(1);
example.setHouseNoStreet("Test");
example.setBuildingName("Test");
example.setLandmark("Test");
List<PaymentDetail> data = new ArrayList<PaymentDetail>();
PaymentDetail paymentDetail = new PaymentDetail();
paymentDetail.setAmount("999.00");
data.add(paymentDetail);
JSONObject jsonObject = new JSONObject(example);
JSONArray jsonArray = new JSONArray(data);
jsonArray.put(data);
System.out.println(jsonArray.put(data));
}
In your test class, what you must do is separate the test data creation to a different class and pass that as data provider to your test method. This is from design point of view.
Coming to your problem:
You are already using gson, why are you constructing a JSONObject. Instead do something like below;
Gson gson = new Gson();
String _my_obj = gson.toJson(example);
Hope this is what you are looking for.

How do I map Retrofit response to Data Model Class?

Here is my Retrofit Call...
public void getContests() {
String token = LoginActivity.authToken;
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(OctoInterface.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
OctoInterface api = retrofit.create(OctoInterface.class);
Call<List<OctoModel2>> call = api.getOctoContests(token);
call.enqueue(new Callback<List<OctoModel2>>() {
#Override
public void onResponse(Call<List<OctoModel2>> call, Response<List<OctoModel2>> response) {
int statusCode = response.code();
int i = 0;
if (response.body().size() > titleList.size()) {
for (i = 0; i <= response.body().size() -1; i++) {
contestIdList.add(String.valueOf(response.body().get(i).getId()));
titleList.add(response.body().get(i).getTitle());
subtitleList.add(response.body().get(i).getDescShort());
offerIdList.add(String.valueOf(response.body().get(i).getId()));
offerLogoList.add(response.body().get(i).getLogoUrl());
businessId = String.valueOf(response.body().get(i).getBusinessId());
submit_button_text = response.body().get(i).getSubmitButtonText();
}
}
}
#Override
public void onFailure(Call<List<OctoModel2>> call, Throwable t) {
Log.e("Get Contest failure", call.toString());
t.printStackTrace();
}
});
}
As you can see, I'm currently grabbing the pieces of the response that I need and passing them to individual array lists. I'd much rather pass the entire return into a list of model objects that hold the data.
Here is my POJO class for retrofit...
public class OctoModel2 {
#SerializedName("how_it_works")
#Expose
private List<String> howItWorks = null;
#SerializedName("id")
#Expose
private int id;
#SerializedName("business_id")
#Expose
private int businessId;
#SerializedName("title")
#Expose
private String title;
#SerializedName("desc_short")
#Expose
private String descShort;
#SerializedName("logo_url")
#Expose
private String logoUrl;
#SerializedName("hashtag")
#Expose
private String hashtag;
#SerializedName("confirm_message_title")
#Expose
private String confirmMessageTitle;
#SerializedName("rules")
#Expose
private String rules;
#SerializedName("confirm_message")
#Expose
private String confirmMessage;
#SerializedName("start_date")
#Expose
private String startDate;
#SerializedName("end_date")
#Expose
private String endDate;
#SerializedName("active")
#Expose
private boolean active;
#SerializedName("entry_count")
#Expose
private int entryCount;
#SerializedName("age_required")
#Expose
private int ageRequired;
#SerializedName("submit_button_text")
#Expose
private String submitButtonText;
#SerializedName("hide_redeem_code")
#Expose
private boolean hideRedeemCode;
#SerializedName("redeem_button_text")
#Expose
private String redeemButtonText;
#SerializedName("rules_text")
#Expose
private String rulesText;
#SerializedName("mode")
#Expose
private String mode;
#SerializedName("entry_mode")
#Expose
private String entryMode;
#SerializedName("created_at")
#Expose
private String createdAt;
#SerializedName("updated_at")
#Expose
private String updatedAt;
#SerializedName("deleted_at")
#Expose
private Object deletedAt;
#SerializedName("locations")
#Expose
private List<Location> locations = null;
#SerializedName("entries")
#Expose
private List<Entry> entries = null;
#SerializedName("entry")
#Expose
private Entry entry;
#SerializedName("AWSAccessKeyId")
#Expose
private String aWSAccessKeyId;
#SerializedName("key")
#Expose
private String key;
#SerializedName("policy")
#Expose
private String policy;
#SerializedName("signature")
#Expose
private String signature;
#SerializedName("uuid")
#Expose
private String uuid;
#SerializedName("reward")
#Expose
private Reward reward;
#SerializedName("s3_url")
#Expose
private String s3_url;
public OctoModel2(Integer id, Integer businessId, String title, String descShort, String logoUrl, String hashtag, String confirmMessageTitle, String rules, String confirmMessage, String startDate, String endDate, Boolean active,
String submitButtonText, String redeemButtonText, String rulesText, List<Location> locations, String aWSAccessKeyId, String key, String policy, String signature, String uuid) {
this.id = id;
this.businessId = businessId;
this.title = title;
this.descShort = descShort;
this.logoUrl = logoUrl;
this.hashtag = hashtag;
this.confirmMessageTitle = confirmMessageTitle;
this.rules = rules;
this.confirmMessage = confirmMessage;
this.startDate = startDate;
this.endDate = endDate;
this.active = active;
this.submitButtonText = submitButtonText;
this.redeemButtonText = redeemButtonText;
this.rulesText = rulesText;
this.locations = locations;
this.aWSAccessKeyId = aWSAccessKeyId;
this.key = key;
this.policy = policy;
this.signature = signature;
this.uuid = uuid;
}
public List<String> getHowItWorks() {
return howItWorks;
}
public void setHowItWorks(List<String> howItWorks) {
this.howItWorks = howItWorks;
}
public int getId() {
return id;
}
public List<OctoModel2> getResults() {
return results;
}
public void setId(int id) {
this.id = id;
}
public int getBusinessId() {
return businessId;
}
public void setBusinessId(int businessId) {
this.businessId = businessId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescShort() {
return descShort;
}
public void setDescShort(String descShort) {
this.descShort = descShort;
}
public String getLogoUrl() {
return logoUrl;
}
public void setLogoUrl(String logoUrl) {
this.logoUrl = logoUrl;
}
public String getHashtag() {
return hashtag;
}
public void setHashtag(String hashtag) {
this.hashtag = hashtag;
}
public String getConfirmMessageTitle() {
return confirmMessageTitle;
}
public void setConfirmMessageTitle(String confirmMessageTitle) {
this.confirmMessageTitle = confirmMessageTitle;
}
public String getRules() {
return rules;
}
public void setRules(String rules) {
this.rules = rules;
}
public String getConfirmMessage() {
return confirmMessage;
}
public void setConfirmMessage(String confirmMessage) {
this.confirmMessage = confirmMessage;
}
public String getStartDate() {
return startDate;
}
public void setStartDate(String startDate) {
this.startDate = startDate;
}
public String getEndDate() {
return endDate;
}
public void setEndDate(String endDate) {
this.endDate = endDate;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public int getEntryCount() {
return entryCount;
}
public void setEntryCount(int entryCount) {
this.entryCount = entryCount;
}
public int getAgeRequired() {
return ageRequired;
}
public void setAgeRequired(int ageRequired) {
this.ageRequired = ageRequired;
}
public String getSubmitButtonText() {
return submitButtonText;
}
public void setSubmitButtonText(String submitButtonText) {
this.submitButtonText = submitButtonText;
}
public boolean isHideRedeemCode() {
return hideRedeemCode;
}
public void setHideRedeemCode(boolean hideRedeemCode) {
this.hideRedeemCode = hideRedeemCode;
}
public String getRedeemButtonText() {
return redeemButtonText;
}
public void setRedeemButtonText(String redeemButtonText) {
this.redeemButtonText = redeemButtonText;
}
public String getRulesText() {
return rulesText;
}
public void setRulesText(String rulesText) {
this.rulesText = rulesText;
}
public String getMode() {
return mode;
}
public void setMode(String mode) {
this.mode = mode;
}
public String getEntryMode() {
return entryMode;
}
public void setEntryMode(String entryMode) {
this.entryMode = entryMode;
}
public String getCreatedAt() {
return createdAt;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
public String getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(String updatedAt) {
this.updatedAt = updatedAt;
}
public Object getDeletedAt() {
return deletedAt;
}
public void setDeletedAt(Object deletedAt) {
this.deletedAt = deletedAt;
}
public List<Location> getLocations() {
return locations;
}
public void setLocations(List<Location> locations) {
this.locations = locations;
}
public List<Entry> getEntries() {
return entries;
}
public void setEntries(List<Entry> entries) {
this.entries = entries;
}
public Entry getEntry() {
return entry;
}
public String getAWSAccessKeyId() {
return aWSAccessKeyId;
}
public void setAWSAccessKeyId(String aWSAccessKeyId) {
this.aWSAccessKeyId = aWSAccessKeyId;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getPolicy() {
return policy;
}
public void setPolicy(String policy) {
this.policy = policy;
}
public String getSignature() {
return signature;
}
public String gets3url() {
return s3_url;
}
public void setSignature(String signature) {
this.signature = signature;
}
public Reward getReward() {
return reward;
}
public void setReward(Reward reward) {
this.reward = reward;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
}
Instead of calling the data from each list like
TitleList.get(position);
SubtitleList.get(position);
LogoUrlList.get(position);
etc...
I'd like to be able to call
Contests.get(position).getTitle();
Contests.get(position).getSubtitle();
Contests.get(position).getLogoUrl();
or however it would be. This would make it better for me to sort the responses and get the data from individual responses without hoping and praying that I'm pulling the correct item from the correct ArrayList.
You need a mapper that maps your DTO (Data Transfer Object) into an entity or list of entities. For example:
public interface Mapper<From, To> {
To map(From value);
}
Now you can create a class, e.g. called `MyRetrofitResponseMapper, that implements the interface and maps the fields needed.
Moreover, you can create multiple mappers that map the same DTO into different entities depending on what DTO fields are required for those.
An example can be found here.

Categories

Resources