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);
}
Related
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.
Hi in the below code modules list is not coming after parsing the json and i have created different pojo classes for different classes and i am not getting the expected json response from server.
Can any one tell me where i did the mistake for json parsing and complete json is not coming as json
Activity.java:
final String username = username1.getText().toString();
final String password = password1.getText().toString();
String operation = "loginAndFetchModules";
final GetNoticeDataService service = RetrofitInstance.getRetrofitInstance().create(GetNoticeDataService.class);
/** Call the method with parameter in the interface to get the notice data*/
Call<LoginAndFetchModules> call1 = service.GetLoginModuleList(operation, username, password);
/**Log the URL called*/
Log.wtf("URL Called", call1.request().url() + "");
call1.enqueue(new Callback<LoginAndFetchModules>() {
#Override
public void onResponse(Call<LoginAndFetchModules> call1, Response<LoginAndFetchModules> response) {
Log.e("response",new Gson().toJson(response.body()));
if (response.isSuccessful()) {
Log.e("response",new Gson().toJson(response.body()));
LoginAndFetchModules loginAndFetchModules = response.body();
String success = loginAndFetchModules.getSuccess();
if (success.equals("true")) {
ArrayList<String> modules = new ArrayList<String>();
try {
JSONArray jsonArray = new JSONArray(loginAndFetchModules);
for (int i = 0; i < jsonArray.length(); i++) {
modules.add(jsonArray.get(i).toString());
JSONObject jsonObject=new JSONObject();
String id=jsonObject.getString("id").toString();
Log.i("id", ":" + id);
String name=jsonObject.getString("name").toString();
Log.i("name", ":" + name);
String isEntity=jsonObject.getString("isEntity").toString();
String label=jsonObject.getString("label").toString();
Log.i("isEntity", ":" + isEntity);
String singular=jsonObject.getString("singular").toString();
Log.i("singular", ":" + singular);
}//end for
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}
LoginAndFetchModules.java:
public class LoginAndFetchModules {
#SerializedName("success")
private String success;
#SerializedName("result")
private List<Results> result;
public List<Results> getResult() {
return result;
}
public void setResult(List<Results> result) {
this.result = result;
}
public String getSuccess() {
return success;
}
public void setSuccess(String success) {
this.success = success;
}
}
Results.java:
public class Results {
#SerializedName("login")
#Expose
private GetLoginListDetails login;
#SerializedName("modules")
#Expose
private ArrayList<LoginListForModules> modules;
public ArrayList<LoginListForModules> getModules() {
return modules;
}
public void setModules(ArrayList<LoginListForModules> modules) {
this.modules = modules;
}
public GetLoginListDetails getLogin() {
return login;
}
public void setLogin(GetLoginListDetails login) {
this.login = login;
}
}
LoginListForModules.java:
public class LoginListForModules {
#SerializedName("id")
#Expose
private String id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("isEntity")
#Expose
private String isEntity;
#SerializedName("label")
#Expose
private String label;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIsEntity() {
return isEntity;
}
public void setIsEntity(String isEntity) {
this.isEntity = isEntity;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getSingular() {
return singular;
}
public void setSingular(String singular) {
this.singular = singular;
}
#SerializedName("singular")
#Expose
private String singular;
}
GetLoginListDetails .java:
public class GetLoginListDetails {
#SerializedName("session")
#Expose
private String session;
#SerializedName("userid")
#Expose
private String userid;
#SerializedName("vtiger_version")
#Expose
private String vtiger_version;
#SerializedName("mobile_module_version")
#Expose
private String mobile_module_version;
public String getSession() {
return session;
}
public void setSession(String session) {
this.session = session;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getVtiger_version() {
return vtiger_version;
}
public void setVtiger_version(String vtiger_version) {
this.vtiger_version = vtiger_version;
}
public String getMobile_module_version() {
return mobile_module_version;
}
public void setMobile_module_version(String mobile_module_version) {
this.mobile_module_version = mobile_module_version;
}
}
Expected output:
{
"success": true,
"result": {
"login": {
"userid": "1",
"session": "fa000f0a6c5a414e62dcc4cbf99175d6",
"vtiger_version": "5.2.0",
"mobile_module_version": "1.2.1"
},
"modules": [
{
"id": "1",
"name": "Calendar",
"isEntity": true,
"label": "Calendar",
"singular": "To Do"
},
{
"id": "2",
"name": "Leads",
"isEntity": true,
"label": "Leads",
"singular": "Lead"
},
{
"id": "3",
"name": "Accounts",
"isEntity": true,
"label": "Accounts",
"singular": "Account"
}]
}
}
According json response, it return Results instead of List. Change your LoginAndFetchModules like below:
public class LoginAndFetchModules {
#SerializedName("success")
private String success;
#SerializedName("result")
private Results result;
public Results getResult() {
return result;
}
public void setResult(Results result) {
this.result = result;
}
public String getSuccess() {
return success;
}
public void setSuccess(String success) {
this.success = success;
}
}
And then parse the informations like below:
if (response.isSuccessful()) {
LoginAndFetchModules loginAndFetchModules = response.body();
String success = loginAndFetchModules.getSuccess();
if (success.equals("true")) {
Results results = loginAndFetchModules.getResult();
//parse login details
GetLoginListDetails loginDetails = results.getLogin();
String userId = loginDetails.getUserid();
//parse modules
ArrayList<LoginListForModules> modules = results.getModules();
//parse module information
for(LoginListForModules module: modules) {
String id = module.getId();
String name = module.getName();
...
}
}
}
you can create classes for response like this
first class is ResultReponse
public class ResultReponse implements Serializable {
#SerializedName("success")
private boolean success;
#SerializedName("result")
private ResultBean result;
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public ResultBean getResult() {
return result;
}
public void setResult(ResultBean result) {
this.result = result;
}
}
ResultBean class
public class ResultBean implements Serializable{
#SerializedName("login")
private LoginBean login;
#SerializedName("modules")
private List<ModulesBean> modules;
public LoginBean getLogin() {
return login;
}
public void setLogin(LoginBean login) {
this.login = login;
}
public List<ModulesBean> getModules() {
return modules;
}
public void setModules(List<ModulesBean> modules) {
this.modules = modules;
}
}
loginBean class inside ResultBean
public class LoginBean implements Serializable {
#SerializedName("userid")
private String userid;
#SerializedName("session")
private String session;
#SerializedName("vtiger_version")
private String vtiger_version;
#SerializedName("mobile_module_version")
private String mobile_module_version;
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getSession() {
return session;
}
public void setSession(String session) {
this.session = session;
}
public String getVtiger_version() {
return vtiger_version;
}
public void setVtiger_version(String vtiger_version) {
this.vtiger_version = vtiger_version;
}
public String getMobile_module_version() {
return mobile_module_version;
}
public void setMobile_module_version(String mobile_module_version) {
this.mobile_module_version = mobile_module_version;
}
}
ModulesBean class in list
public class ModulesBean implements Serializable {
#SerializedName("id")
private String id;
#SerializedName("name")
private String name;
#SerializedName("isEntity")
private boolean isEntity;
#SerializedName("label")
private String label;
#SerializedName("singular")
private String singular;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isIsEntity() {
return isEntity;
}
public void setIsEntity(boolean isEntity) {
this.isEntity = isEntity;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getSingular() {
return singular;
}
public void setSingular(String singular) {
this.singular = singular;
}
}
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.
The problem here is that the same request works fine after restarting the server.
This is the stackTrace error
Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Can not deserialize instance of java.lang.String out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token
This is the request Handler
#PostMapping("/buy-data")
#ApiOperation(value = "Guest buy data")
public ResponseEntity<?> buyData(#Valid #RequestBody BuyDataPaymentDto
paymentDto, Errors errors,#RequestParam(defaultValue = "web") String channel)
{
...
}
This is the BuyDataPaymentDto
public class BuyDataPaymentDto {
private long productId;
private String transactionId;
private String status;
private long paymentId;
private String cardLast4Digit;
private long networkId;
private String transactionRef;
#NotEmpty(message = "Receiver's msisdn cannot be blank")
private String receiverMsisdn;
public BuyDataPaymentDto() {
}
public long getProductId() {
return productId;
}
public void setProductId(long productId) {
this.productId = productId;
}
public String getTransactionId() {
return transactionId;
}
public void setTransactionId(String transactionId) {
this.transactionId = transactionId;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public long getPaymentId() {
return paymentId;
}
public void setPaymentId(long paymentId) {
this.paymentId = paymentId;
}
public String getCardLast4Digit() {
return cardLast4Digit;
}
public void setCardLast4Digit(String cardLast4Digit) {
this.cardLast4Digit = cardLast4Digit;
}
public long getNetworkId() {
return networkId;
}
public void setNetworkId(long networkId) {
this.networkId = networkId;
}
public String getTransactionRef() {
return transactionRef;
}
public void setTransactionRef(String transactionRef) {
this.transactionRef = transactionRef;
}
public String getReceiverMsisdn() {
return receiverMsisdn;
}
public void setReceiverMsisdn(String receiverMsisdn) {
this.receiverMsisdn = receiverMsisdn;
}
}
I have following JSON string that I need to set to the Java objects of POJO class.
What method should I follow?
{"status":"FOUND","messages":null,"sharedLists": [{"listId":"391647d","listName":"/???","numberOfItems":0,"colla borative":false,"displaySettings":true}] }
I tried using Gson but it did not work for me.
Gson gson = new Gson();
SharedLists target = gson.fromJson(sb.toString(), SharedLists.class);
Following is my SharedLists pojo
public class SharedLists {
#SerializedName("listId")
private String listId;
#SerializedName("listName")
private String listName;
#SerializedName("numberOfItems")
private int numberOfItems;
#SerializedName("collaborative")
private boolean collaborative;
#SerializedName("displaySettings")
private boolean displaySettings;
public int getNumberOfItems() {
return numberOfItems;
}
public void setNumberOfItems(int numberOfItems) {
this.numberOfItems = numberOfItems;
}
public boolean isCollaborative() {
return collaborative;
}
public void setCollaborative(boolean collaborative) {
this.collaborative = collaborative;
}
public boolean isDisplaySettings() {
return displaySettings;
}
public void setDisplaySettings(boolean displaySettings) {
this.displaySettings = displaySettings;
}
public String getListId() {
return listId;
}
public void setListId(String listId) {
this.listId = listId;
}
}
Following is your JSON string.
{
"status": "FOUND",
"messages": null,
"sharedLists": [
{
"listId": "391647d",
"listName": "/???",
"numberOfItems": 0,
"colla borative": false,
"displaySettings": true
}
]
}
Clearly sharedLists is a JSON array within the outer JSON object.
So I have two classes as follows (created from http://www.jsonschema2pojo.org/ by providing your JSON as input)
ResponseObject - Represents the outer object
public class ResponseObject {
#SerializedName("status")
#Expose
private String status;
#SerializedName("messages")
#Expose
private Object messages;
#SerializedName("sharedLists")
#Expose
private List<SharedList> sharedLists = null;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Object getMessages() {
return messages;
}
public void setMessages(Object messages) {
this.messages = messages;
}
public List<SharedList> getSharedLists() {
return sharedLists;
}
public void setSharedLists(List<SharedList> sharedLists) {
this.sharedLists = sharedLists;
}
}
and the SharedList - Represents each object within the array
public class SharedList {
#SerializedName("listId")
#Expose
private String listId;
#SerializedName("listName")
#Expose
private String listName;
#SerializedName("numberOfItems")
#Expose
private Integer numberOfItems;
#SerializedName("colla borative")
#Expose
private Boolean collaBorative;
#SerializedName("displaySettings")
#Expose
private Boolean displaySettings;
public String getListId() {
return listId;
}
public void setListId(String listId) {
this.listId = listId;
}
public String getListName() {
return listName;
}
public void setListName(String listName) {
this.listName = listName;
}
public Integer getNumberOfItems() {
return numberOfItems;
}
public void setNumberOfItems(Integer numberOfItems) {
this.numberOfItems = numberOfItems;
}
public Boolean getCollaBorative() {
return collaBorative;
}
public void setCollaBorative(Boolean collaBorative) {
this.collaBorative = collaBorative;
}
public Boolean getDisplaySettings() {
return displaySettings;
}
public void setDisplaySettings(Boolean displaySettings) {
this.displaySettings = displaySettings;
}
}
Now you can parse the entire JSON string with GSON as follows
Gson gson = new Gson();
ResponseObject target = gson.fromJson(inputString, ResponseObject.class);
Hope this helps.