I have an app that is to register people into a platform but I get a response of Unauthenticated each time I submit the form data. The form is submitted using an API which requires a bearer token for each post request with the aid of retrofit. I have been out of touch with Java.
Note: its just a plain form. No authentication has been implemented in the app.
My ApiClient.java class
public class ApiClient {
private static Retrofit getRetrofit(){
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(httpLoggingInterceptor).build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("xxxxxxxxxxxxx")
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build();
return retrofit;
}
public static UserService getUserService(){
UserService userService = getRetrofit().create(UserService.class);
return userService;
}
}
My UserService.java class
public interface UserService {
#POST("algonapi/api/enroll_vehicle")
Call<UserResponse> saveUser(#Body UserRequest userRequest);
}
My saveUser Method
public void saveUser(UserRequest userRequest){
Call<UserResponse> userResponseCall = ApiClient.getUserService().saveUser(userRequest);
userResponseCall.enqueue(new Callback<UserResponse>() {
#Override
public void onResponse(Call<UserResponse> call, Response<UserResponse> response) {
if (response.isSuccessful()){
Toast.makeText(MainActivity.this, "Registration Successfull! Click on Reset Form to Start a New Enumeration...", Toast.LENGTH_LONG).show();
}else {
Toast.makeText(MainActivity.this, "Registration Failed!", Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<UserResponse> call, Throwable t) {
Toast.makeText(MainActivity.this, "Registration Failed!" +t.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
});
}
My UserRequest
package com.example.xxxxx;
public class UserRequest {
private String FullName;
private String StickerNumber;
private String Address;
private String Email;
private String Phone;
private String Nationality;
private String State;
private String LGA;
private String RC;
private String DriversLicenseNo;
private String LicenseIssued;
private String LicenseExpiry;
private String VehicleType;
private String VehicleLicense;
private String VehicleTyres;
private String LGAofOperation;
private String NOKFullName;
private String NOKAddress;
private String NOKPhone;
private String NOKEmail;
private String NOKNationality;
private String NOKState;
public String getFullName() {
return FullName;
}
public void setFullName(String fullName) {
FullName = fullName;
}
public String getStickerNumber() {
return StickerNumber;
}
public void setStickerNumber(String stickerNumber) {
StickerNumber = stickerNumber;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public String getPhone() {
return Phone;
}
public void setPhone(String phone) {
Phone = phone;
}
public String getNationality() {
return Nationality;
}
public void setNationality(String nationality) {
Nationality = nationality;
}
public String getState() {
return State;
}
public void setState(String state) {
State = state;
}
public String getLGA() {
return LGA;
}
public void setLGA(String LGA) {
this.LGA = LGA;
}
public String getRC() {
return RC;
}
public void setRC(String RC) {
this.RC = RC;
}
public String getDriversLicenseNo() {
return DriversLicenseNo;
}
public void setDriversLicenseNo(String driversLicenseNo) {
DriversLicenseNo = driversLicenseNo;
}
public String getLicenseIssued() {
return LicenseIssued;
}
public void setLicenseIssued(String licenseIssued) {
LicenseIssued = licenseIssued;
}
public String getLicenseExpiry() {
return LicenseExpiry;
}
public void setLicenseExpiry(String licenseExpiry) {
LicenseExpiry = licenseExpiry;
}
public String getVehicleType() {
return VehicleType;
}
public void setVehicleType(String vehicleType) {
VehicleType = vehicleType;
}
public String getVehicleLicense() {
return VehicleLicense;
}
public void setVehicleLicense(String vehicleLicense) {
VehicleLicense = vehicleLicense;
}
public String getVehicleTyres() {
return VehicleTyres;
}
public void setVehicleTyres(String vehicleTyres) {
VehicleTyres = vehicleTyres;
}
public String getLGAofOperation() {
return LGAofOperation;
}
public void setLGAofOperation(String LGAofOperation) {
this.LGAofOperation = LGAofOperation;
}
public String getNOKFullName() {
return NOKFullName;
}
public void setNOKFullName(String NOKFullName) {
this.NOKFullName = NOKFullName;
}
public String getNOKAddress() {
return NOKAddress;
}
public void setNOKAddress(String NOKAddress) {
this.NOKAddress = NOKAddress;
}
public String getNOKPhone() {
return NOKPhone;
}
public void setNOKPhone(String NOKPhone) {
this.NOKPhone = NOKPhone;
}
public String getNOKEmail() {
return NOKEmail;
}
public void setNOKEmail(String NOKEmail) {
this.NOKEmail = NOKEmail;
}
public String getNOKNationality() {
return NOKNationality;
}
public void setNOKNationality(String NOKNationality) {
this.NOKNationality = NOKNationality;
}
public String getNOKState() {
return NOKState;
}
public void setNOKState(String NOKState) {
this.NOKState = NOKState;
}
}
Create the OkHttpClient like this
OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
#NotNull
#Override
public Response intercept(#NotNull Chain chain) throws IOException {
Request request=chain.request().newBuilder()
.addHeader("Authorization", "Bearer " + token)
.build();
return chain.proceed(request);
}
}).build();
If you most of your https requests need authentication then the first answer is perfect but if some of your requests need then you can pass the header to each methods.
public interface UserService {
#POST("algonapi/api/enroll_vehicle")
Call<UserResponse> saveUser(
#Header("Authorization") String token,
#Body UserRequest userRequest
);
}
While calling the method simply pass your token along with userRequest.
Related
I am Trying to write test case for a method which takes URI as input and maps with modelmapper.
however, I am getting null pointer exception for this.
I have added every possible implementaion of class which I want to test.
if you guy's need more for compilation tell me in comment section.
this one is actual implementation which I want to mock
#Override
public ApplicationScanConfigDTO getApplicationScanConfig(int account_id, String appAppScanConfigId) {
URI getUri = UriComponentsBuilder.fromPath("/").pathSegment("api/scheduleOnDemand")
.queryParam("Account_Id", account_id).queryParam("applicationConfigScanId", appAppScanConfigId).build()
.toUri();
return modelMapper.map(apiClient.getOperation(getUri, Object.class), ApplicationScanConfigDTO.class);
}
This is what I was trying
#Test
void testGetApplicationScanConfig() throws Exception {
URI getUri = new URI("/api/scheduleOnDemand?Account_Id=1&applicationConfigScanId=1");
modelmapper.map(restTemplate.getForEntity(getUri, JSONObject.class), ApplicationScanConfigDTO.class);
}
apiclient implementation
#Override
public <R> R getOperation(URI uri, Class<R> rClasss) {
URI builder = UriComponentsBuilder.fromHttpUrl(baseUrl)
.path(uri.getPath())
.query(uri.getQuery())
.build()
.toUri();
return restTemplate.getForObject(builder, rClasss);
}
ApplicationConfigDTO actual implementation:
public class ApplicationScanConfigDTO {
private Integer id;
private String serverName;
private Integer accountId;
private String ipAddress;
private String subnetRange;
private Integer credentialId;
private String credentialName;
private String os;
private List<String> ibmLibrary;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getServerName() {
return serverName;
}
public void setServerName(String serverName) {
this.serverName = serverName;
}
public Integer getAccountId() {
return accountId;
}
public void setAccountId(Integer accountId) {
this.accountId = accountId;
}
public String getIpAddress() {
return ipAddress;
}
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
public String getSubnetRange() {
return subnetRange;
}
public void setSubnetRange(String subnetRange) {
this.subnetRange = subnetRange;
}
public Integer getCredentialId() {
return credentialId;
}
public void setCredentialId(Integer credentialId) {
this.credentialId = credentialId;
}
public String getCredentialName() {
return credentialName;
}
public void setCredentialName(String credentialName) {
this.credentialName = credentialName;
}
public String getOs() {
return os;
}
public void setOs(String os) {
this.os = os;
}
public List<String> getIbmLibrary() {
return ibmLibrary;
}
public void setIbmLibrary(List<String> ibmLibrary) {
this.ibmLibrary = ibmLibrary;
}
}
I'm using retrofit2 and Rxjava2 to insert/get information from mongodb and nodeJs server, for now, I receive all data as a string but I want to get hole collection Infos from my base so I need to convert string to JSON and get each information.
My code to receive data:
1- Service:
#POST("collect/get")
#FormUrlEncoded
Observable<String> getcollection(#Field("selector") String selector);
2-RetrofitClient:
if(instance == null){
instance = new Retrofit.Builder()
.baseUrl("http://transportor.ddns.net:3000/")
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(ScalarsConverterFactory.create()).build();
}
3- Recieve function
private void getallcollection(String selector) {
compositeDisposable.add(myServices.getcollection(selector)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<String>(){
#Override
public void accept(String s) throws Exception {
Log.d("infos",s);
}
}));
}
I'm already prepared Collection class:
public class col {
private String creator;
private String emailcol;
private String date_creation_col;
private String nom_col;
private String long_col;
private String lat_col;
private String tel_fix_col;
private String tel_mobile_col;
private String creatorcreator;
private String heure_matin_col;
private String heure_apresmatin_col;
private String type;
private String imagePath;
public col(String creator, String emailcol, String date_creation_col, String nom_col, String long_col, String lat_col, String tel_fix_col, String tel_mobile_col, String creatorcreator, String heure_matin_col, String heure_apresmatin_col, String type, String imagePath) {
this.creator = creator;
this.emailcol = emailcol;
this.date_creation_col = date_creation_col;
this.nom_col = nom_col;
this.long_col = long_col;
this.lat_col = lat_col;
this.tel_fix_col = tel_fix_col;
this.tel_mobile_col = tel_mobile_col;
this.creatorcreator = creatorcreator;
this.heure_matin_col = heure_matin_col;
this.heure_apresmatin_col = heure_apresmatin_col;
this.type = type;
this.imagePath = imagePath;
}
public String getCreator() {
return creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
public String getEmailcol() {
return emailcol;
}
public void setEmailcol(String emailcol) {
this.emailcol = emailcol;
}
public String getDate_creation_col() {
return date_creation_col;
}
public void setDate_creation_col(String date_creation_col) {
this.date_creation_col = date_creation_col;
}
public String getNom_col() {
return nom_col;
}
public void setNom_col(String nom_col) {
this.nom_col = nom_col;
}
public String getLong_col() {
return long_col;
}
public void setLong_col(String long_col) {
this.long_col = long_col;
}
public String getLat_col() {
return lat_col;
}
public void setLat_col(String lat_col) {
this.lat_col = lat_col;
}
public String getTel_fix_col() {
return tel_fix_col;
}
public void setTel_fix_col(String tel_fix_col) {
this.tel_fix_col = tel_fix_col;
}
public String getTel_mobile_col() {
return tel_mobile_col;
}
public void setTel_mobile_col(String tel_mobile_col) {
this.tel_mobile_col = tel_mobile_col;
}
public String getCreatorcreator() {
return creatorcreator;
}
public void setCreatorcreator(String creatorcreator) {
this.creatorcreator = creatorcreator;
}
public String getHeure_matin_col() {
return heure_matin_col;
}
public void setHeure_matin_col(String heure_matin_col) {
this.heure_matin_col = heure_matin_col;
}
public String getHeure_apresmatin_col() {
return heure_apresmatin_col;
}
public void setHeure_apresmatin_col(String heure_apresmatin_col) {
this.heure_apresmatin_col = heure_apresmatin_col;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getImagePath() {
return imagePath;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
}
Actually I received all data and console show me : [{"_id":"5e22074673c926147c3a73f5","date_creation_col":"17-01-2020","creator":"Alaeddine","emailcol":"amir#gmail.com","nom_col":"amir","long_col":"10.179326869547367","lat_col":"36.83353893150942","tel_fix_col":"123","tel_mobile_col":"1234","adress_col":"rue Paris mision 34","heure_matin_col":"7","heure_apresmatin_col":"5","type":"collection","imagePath":"mmmmmmmmmmmm"}]
I want to know how to extract for example creator from this Json.
You can use a third-party JSON parser, like Google GSON, as you're already developing for Android. Java does not seem to contain a built-in JSON parser.
See this answer.
Am using retrofit and RxJava to Connect to API. Data is being successfully posted to Server but i would like to get the Token which the API generates after posting data.
This is for Authentication of user using a JSON Web Token Django Backend
The models are working fine but Here are my Models:
public class User {
#SerializedName("user")
#Expose
private User_ user;
public User_ getUser() {
return user;
}
public void setUser(User_ user) {
this.user = user;
}
#Override
public String toString() {
return new ToStringBuilder(this).append("user", user).toString();
}
}
public class User_ {
#SerializedName("email")
#Expose
private String email;
#SerializedName("password")
#Expose
private String password;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Override
public String toString() {
return new ToStringBuilder(this).append("email", email).append("password", password).toString();
}
}
#SerializedName("user")
#Expose
private LoginResponse_ user;
public LoginResponse_ getUser() {
return user;
}
public void setUser(LoginResponse_ user) {
this.user = user;
}
#Override
public String toString() {
return new ToStringBuilder(this).append("user", user).toString();
}
}
public class LoginResponse_ {
#SerializedName("email")
#Expose
private String email;
#SerializedName("token")
#Expose
private String token;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
#Override
public String toString() {
return new ToStringBuilder(this).append("email", email).append("token", token).toString();
}
}
Retrofit Interface
#POST("auth/login")
#Headers("X-Requested-With:XMLHttpRequest")
Observable<User> login(
#Header("Content-Type") String content_type,
#Body User user
);
}
Retrofit Adapter
public class ServiceGenerator {
private static Retrofit retrofit;
private static Gson gson;
public static synchronized Retrofit getUser() {
if (retrofit == null) {
if (gson == null) {
gson = new GsonBuilder().setLenient().create();
}
retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
}
return retrofit;
}
Retrofit Instance
public class NetworkUtils {
private static UserService userService;
public static UserService ApiInstance(){
if (userService == null){
userService = ServiceGenerator.getUser().create(UserService.class);
}
return userService;
}
}
This is how am trying to login the user
private void loginProcess(String email, String password) {
User user = new User();
User_ user_ = new User_();
user_.setEmail(email);
user_.setPassword(password);
user.setUser(user_);
mUserService.login("application/json", user)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(new Observer<User>() {
#Override
public void onSubscribe(Disposable d) {
}
#Override
public void onNext(User user) {
showResponse(user.toString());
Log.i(TAG, "Response: "+ user);
mProgressBar.setVisibility(View.GONE);
handleResponse();
}
#Override
public void onError(Throwable e) {
e.printStackTrace();
}
#Override
public void onComplete() {
}
});
}
private void handleResponse(LoginResponse response) {
SharedPreferences.Editor editor = mSharedPreference.edit();
editor.putString(Constants.TOKEN,response.getUser().getToken());
editor.putString(Constants.EMAIL,response.getUser().getEmail());
editor.apply();
mEditTextEmail.setText(null);
mEditTextPassword.setText(null);
Intent intent = new Intent(getActivity(),ProfileActivity.class);
startActivity(intent);
}
It would be really helpful if i get to know how to get response after posting the data to the API.
Using postman this is what i post
{"user":{"email":"user#email.com", "password":"userpassword"}}
And this is the response I get
{
"user": {
"email": "user#email.com",
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6NSwiZXhwIjoxNTY5MjI5NTgxfQ.S-1yZWNhx_TV8uay8PubGoq9XMpyTIn_ipG8A6DWTfE"
}
}
I want to register a user with their token, I want to register a user using retrofit in android but I keep getting this error:
ERROR::: Attempt to invoke virtual method 'void com.signup.User.setUsername(java.lang.String)' on a null object reference
Here is my code:
public class Session {
Context context;
private SharedPreferences prefs;
public Session(Context cntx) {
// TODO Auto-generated constructor stub
this.context = cntx;
prefs = PreferenceManager.getDefaultSharedPreferences(context);
}
public void setJwtToken(String token) {
prefs.edit().putString("JwtToken", token).commit();
}
public String getJwtToken() {
String token = prefs.getString("JwtToken", "");
if (token == null || token.isEmpty()) {
token = "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjIxNzc0NTI3OTksImlhdCI6MTUxNjAyMjk5OSwiaXNzIjoiQmFzb2JhYXMgTmVwYWwiLCJuYmYiOjE1MTYwMjI5OTksImp0aSI6Ikd1ZXN0VG9rZW4iLCJzdWIiOjB9.QikmNgBYmqch5HREGFEpUs4Xk3x-zFfDg5mhYJO7jM8";
}
return token;
}
}
public interface ApiInterface {
#POST("/api/users/signup")
Call<ResponseBody> signMeUp(#Header("Authorization") String token ,#Body User user);
}
public class MainActivity extends AppCompatActivity {
private EditText et_name, et_address, et_phone, et_username, et_email, et_password, et_confipassword;
private Button register;
private User user;
private SharedPreferences prefs;
private ApiInterface apiInterface;
private Session session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_name = findViewById(R.id.edit_text_name);
et_address = findViewById(R.id.edit_text_address);
et_phone = findViewById(R.id.edit_text_phonenumber);
et_username = findViewById(R.id.edit_text_username);
et_email = findViewById(R.id.edit_text_email);
et_password = findViewById(R.id.edit_text_password);
et_confipassword = findViewById(R.id.edit_text_confirm_password);
register = findViewById(R.id.signupButton);
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Login();
}
});
}
private void Login() {
user.setUsername(et_name.getText().toString());
user.setAddress(et_address.getText().toString());
user.setPhone(et_phone.getText().toString());
user.setName(et_name.getText().toString());
user.setEmail(et_email.getText().toString());
user.setPassword(et_password.getText().toString());
user.setPasswordConfirmation(et_confipassword.getText().toString());
signupUser(user);
}
private void signupUser(final User user) {
// Set up progressbar before call
apiInterface = ApiClient.getClient().create(ApiInterface.class);
Call<ResponseBody> call1 = apiInterface.signMeUp(session.getJwtToken(),user);
final Gson gson = new Gson();
final String json = gson.toJson(user);
call1.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.code() == 201) {
try {
JSONObject jsonObject = new JSONObject(response.body().string());
//Starting main activity after user sees dialog
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else if (response.code() == 500) {
try {
JSONObject jsonObject = new JSONObject(response.errorBody().string());
Log.e("SignupFragment", jsonObject.toString());
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}else
Log.e("SignupFragment", response.raw().toString());
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
}
}
public class User {
#SerializedName("name")
#Expose
private String name;
#SerializedName("email")
#Expose
private String email;
#SerializedName("password")
#Expose
private String password;
#SerializedName("password_confirmation")
#Expose
private String passwordConfirmation;
#SerializedName("image")
#Expose
private String image;
#SerializedName("phone")
#Expose
private String phone;
#SerializedName("address")
#Expose
private String address;
#SerializedName("username")
#Expose
private String username;
#SerializedName("pan_no")
#Expose
private String panNo;
#SerializedName("birthday")
#Expose
private String birthday;
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 getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPasswordConfirmation() {
return passwordConfirmation;
}
public void setPasswordConfirmation(String passwordConfirmation) {
this.passwordConfirmation = passwordConfirmation;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPanNo() {
return panNo;
}
public void setPanNo(String panNo) {
this.panNo = panNo;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
}
public class ApiClient {
public static final String BASE_URL = "https://myapp.herokuapp.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;
}
ApiInterface apiInterface=retrofit.create(ApiInterface.class);
}
I want to signup a user via my app but I keep getting the error. And, if I remove the auth from header from my Interface I get a message asking a token, and when I provide a token it give me a null object reference error !!
You should instantiate variable before access it: User user = new User();
Update: do it in void Login()
create an instance of User inside onCreate method or up there where it's declared
Try this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
user = new User();
session = new Session(this);
}
i'm trying to get a JSON from my web service and deserialize to my class UserSync, but i'm getting the following error:
Can not instantiate value of type [simple type, class com.example.breno.teste.model.User] from String value (''); no single-String constructor/factory method
at [Source: okhttp3.ResponseBody$BomAwareReader#fbf814f; line: 1, column: 86] (through reference chain: com.example.breno.teste.dto.UserSync["user"])
I've read some posts saying that i need to declare my User class static in UserSync, but when i do that, jackson can't find any user property, even with JsonDescription. Another posts say that i may need to declare a default constructor, so i did.
Here is the UserSync class:
#JsonIgnoreProperties(ignoreUnknown = true)
public class UserSync {
#JsonProperty("status")
private String Status;
#JsonProperty("currentDate")
private String CurrentDate;
#JsonProperty("message")
private String Message;
#JsonProperty("user")
private static User NewUser;
public UserSync() {
}
public String getStatus() {
return Status;
}
public String getCurrentDate() {
return CurrentDate;
}
public String getMessage() {
return Message;
}
public static User getNewUser() {
return NewUser;
}
The User class:
public class User implements Serializable {
#JsonProperty("userKey")
private UUID UserKey;
#JsonProperty("userPassword")
private String UserPassword;
#JsonProperty("userGroupKey")
private UUID UserGroupKey;
#JsonProperty("signInDate")
private String SignInDate;
#JsonProperty("active")
private boolean Active;
#JsonProperty("profilePicturePath")
private String ProfilePic;
#JsonProperty("completeName")
private String UserCompleteName;
#JsonProperty("email")
private String UserEmail;
#JsonProperty("isLogged")
private boolean IsLogged;
public User() {
}
public boolean getIsLogged() {
return IsLogged;
}
public void setIsLogged(boolean isLogged) {
IsLogged = isLogged;
}
public String getUserEmail() {
return UserEmail;
}
public void setUserEmail(String userEmail) {
UserEmail = userEmail;
}
public UUID getUserKey() {
return UserKey;
}
public void setUserKey(UUID userKey) {
UserKey = userKey;
}
public String getUserPassword() {
return UserPassword;
}
public void setUserPassword(String userPassword) {
UserPassword = userPassword;
}
public UUID getUserGroupKey() {
return UserGroupKey;
}
public void setUserGroupKey(UUID userGroupKey) {
UserGroupKey = userGroupKey;
}
public String getSignInDate() {
return SignInDate;
}
public void setSignInDate(String signInDate) {
SignInDate = signInDate;
}
public boolean getActive() {
return Active;
}
public void setActive(boolean active) {
Active = active;
}
public String getProfilePic() {
return ProfilePic;
}
public void setProfilePic(String profilePic) {
ProfilePic = profilePic;
}
public String getUserCompleteName() {
return UserCompleteName;
}
public void setUserCompleteName(String userCompleteName) {
UserCompleteName = userCompleteName;
}
}
My service class (Using now the postNewUser):
public interface UserService {
#GET("Login/LoginUser?")
Call<UserSync> login(#Query("email") String email, #Query("password") String password);
//region NewUser Services
#GET("Login/VerifyNewUser?")
Call<UserSync> validateNewUser(#Query("email") String email);
#POST("Login/PostNewUser")
Call<UserSync> postNewUser(#Body User user);
//endregion
}
And finally, the JSON:
{
"status": "OK",
"currentDate": "20/07/2017 11:59:02",
"message": "teste",
"user": {
"userKey": "8e2f0d2d-3522-472d-be1d-28791367f4ee",
"email": "teste_teste#hotmail.com",
"userPassword": "123456",
"profilePicturePath": "teste",
"completeName": "Jorge",
"userGroupKey": null,
"signInDate": "2017-07-07T16:26:06.097",
"active": true,
"isLogged": true
}
}
Can someone help me, please?
EDIT 1 - Here is the method that i'm using to do the retrofit call:
public void register(User user) {
Call<UserSync> postCall = new RetrofitInitializator().getUserService().postNewUser(user);
postCall.enqueue(getRegisterCallback());
}
#NonNull
private Callback<UserSync> getRegisterCallback() {
return new Callback<UserSync>() {
#Override
public void onResponse(Call<UserSync> call, Response<UserSync> response) {
User user = response.body().getNewUser();
}
#Override
public void onFailure(Call<UserSync> call, Throwable t) {
Log.e("Register - onFailure", t.getMessage());
}
};
}
EDIT 2 - The retrofitInicializator class:
public class RetrofitInitializator {
private final Retrofit retrofit;
public RetrofitInitializator() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder builder = new OkHttpClient
.Builder();
builder.addInterceptor(interceptor);
retrofit = new Retrofit.Builder()
.baseUrl("http://192.168.15.6:7071/api/")
.addConverterFactory(JacksonConverterFactory.create())
.client(builder.build())
.build();
}
public UserService getUserService() {
return retrofit.create(UserService.class);
}
}
I managed to resolve my problem switching the type User to JsonNode and doing the convertion after this.
#JsonProperty("status")
private String Status;
#JsonProperty("currentDate")
private String CurrentDate;
#JsonProperty("message")
private String Message;
#JsonProperty("user")
private JsonNode NewUser;
and the convertion:
private User getUserFromUserAsync(UserSync userSync) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
return mapper.treeToValue(userSync.getNewUser(), User.class);
}