The parsing is successful but problem is ,it is taking loggedinClients only,ActiveClients not getting in retrofit , how can we parse array under array and with no object name?
{
"status": 200,
"success": true,
"messages": "",
"result": [
[
{
"LoggedinClients": 1
}
],
[
{
"ActiveClients": 0
}
]
]
}
partly Related Code:
public class OnlineInfoResponse {
#SerializedName("result")
#Expose
private List<List<OnlineInfoLoggedInResult>> lstLists = null;
public List<List<OnlineInfoLoggedInResult>> getLstLoggedIn() {
return lstLists;
}
public void setLstLists(List<List<OnlineInfoLoggedInResult>> lstLists) {
this.lstLists = lstLists;
}
OnlineInfoLoggedInResult.java
public class OnlineInfoLoggedInResult {
#SerializedName("LoggedinClients")
#Expose
private int loggedinClients;
public int getLoggedinClients() {
return loggedinClients;
}
public void setLoggedinClients(int loggedinClients) {
this.loggedinClients = loggedinClients;
}
#SerializedName("ActiveClients")
#Expose
private int activeClients;
public int getActiveClients() {
return activeClients;
}
public void setActiveClients(int activeClients) {
this.activeClients = activeClients;
}
}
this i got parsing from jsonschema.I am having problem in nested jsonarray.
You should generate the following POJO
public class YourPojoName {
private float status;
private boolean success;
private String messages;
List <List< Object> > result = new ArrayList < ArrayList<Object> > ();
// Getter Methods
public float getStatus() {
return status;
}
public boolean getSuccess() {
return success;
}
public String getMessages() {
return messages;
}
// Setter Methods
public void setStatus(float status) {
this.status = status;
}
public void setSuccess(boolean success) {
this.success = success;
}
public void setMessages(String messages) {
this.messages = messages;
}
}
public class abbb {
#Expose
#SerializedName("result")
private List<List<Result>> result;
#Expose
#SerializedName("messages")
private String messages;
#Expose
#SerializedName("success")
private boolean success;
#Expose
#SerializedName("status")
private int status;
public List<List<Result>> getResult() {
return result;
}
public void setResult(List<List<Result>> result) {
this.result = result;
}
public String getMessages() {
return messages;
}
public void setMessages(String messages) {
this.messages = messages;
}
public boolean getSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public static class Result {
#Expose
#SerializedName("LoggedinClients")
private int LoggedinClients;
#Expose
#SerializedName("ActiveClients")
private int active_clients;
//genetrate getter setter
}
}
Related
Am new to Retrofit and API Integration. Am trying to display response in a toast. Am using Retrofit for an API call. But the response from Retrofit is showing null . There is no response instead null. I don't Know may be am doing in a wrong way. Here is my code. Please Help me
Below is sample API
Params:
{
"DeviceID": "Hawqr-jagadish-test-device",
"DeviceType": "1",
"DeviceName": "Jagadish Device",
"AppVersion": 1
}
Response:
{
"success": true,
"extras": {
"Status": "Device Splash Screen Completed Successfully",
"Env_Type": 2,
"ApiKey": "4ae3a7e5-2622-4376-bc0d-a0ccd6c0405a",
"Whether_Latest_Version": true,
"SocketIO_Data": {
"socket_host": "https://xsocket.hawqr.com",
"socketjs_link": "https://xsocket.hawqr.com/socket.io/socket.io.js"
}
}
}
This My Main Activity. In main activity i have call API
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(MainActivity.this,LoginActivity.class);
startActivity(intent);
finish();
}
},SPLASH_SCREEN );
String DeviceID = "Hawqr-jagadish-test-device";
String DeviceType = "1";
String DeviceName = "Jagadish Device";
Integer AppVersion = 1 ;
SplashRequest splashRequest = new SplashRequest();
splashRequest.setDeviceID(DeviceID);
splashRequest.setDeviceType(DeviceType);
splashRequest.setDeviceName(DeviceName);
splashRequest.setAppVersion(AppVersion);
SplashScreen(splashRequest);
}
public void SplashScreen(SplashRequest splashRequest){
UserService userService = ApiClient.getRetrofit().create(UserService.class);
Call<SplashResponse> splashResponseCall = userService.splashScreen(splashRequest);
splashResponseCall.enqueue(new Callback<SplashResponse>() {
#Override
public void onResponse(Call<SplashResponse> call, Response<SplashResponse> response) {
Gson gson = new Gson();
String successResponse = gson.toJson(response.body());
Toast.makeText(MainActivity.this,successResponse,Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(Call<SplashResponse> call, Throwable t) {
String msg = t.getLocalizedMessage();
Toast.makeText(MainActivity.this,msg,Toast.LENGTH_SHORT).show();
}
});
}
}
These are my Model classes for Parameters
public class SplashRequest {
public String DeviceID;
public String DeviceType;
public String DeviceName;
public Integer AppVersion;
public String getDeviceID() {
return DeviceID;
}
public void setDeviceID(String deviceID) {
DeviceID = deviceID;
}
public String getDeviceType() {
return DeviceType;
}
public void setDeviceType(String deviceType) {
DeviceType = deviceType;
}
public String getDeviceName() {
return DeviceName;
}
public void setDeviceName(String deviceName) {
DeviceName = deviceName;
}
public Integer getAppVersion() {
return AppVersion;
}
public void setAppVersion(Integer appVersion) {
AppVersion = appVersion;
}
Another Model Class
public String ApiKey;
public String Env_Type;
public String Status;
public String Whether_Latest_Version;
public SplashResponse(String apiKey, String env_Type, String status, String whether_Latest_Version) {
ApiKey = apiKey;
Env_Type = env_Type;
Status = status;
Whether_Latest_Version = whether_Latest_Version;
}
public String getApiKey() {
return ApiKey;
}
public void setApiKey(String apiKey) {
ApiKey = apiKey;
}
public String getEnv_Type() {
return Env_Type;
}
public void setEnv_Type(String env_Type) {
Env_Type = env_Type;
}
public String getStatus() {
return Status;
}
public void setStatus(String status) {
Status = status;
}
public String getWhether_Latest_Version() {
return Whether_Latest_Version;
}
public void setWhether_Latest_Version(String whether_Latest_Version) {
Whether_Latest_Version = whether_Latest_Version;
}
}
This My Interface Class for Splash Response and Request
#POST("authenticate/")
Call<SplashResponse> splashScreen(#Body SplashRequest splashRequest);
The model class Splash Response was wrong, I made changes to it and its working fine.
public class SplashResponse implements Serializable {
#SerializedName("success")
#Expose
private Boolean success;
#SerializedName("extras")
#Expose
private Extras extras;
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public Extras getExtras() {
return extras;
}
public void setExtras(Extras extras) {
this.extras = extras;
}
public class Extras {
#SerializedName("Status")
#Expose
private String status;
#SerializedName("Env_Type")
#Expose
private Integer envType;
#SerializedName("ApiKey")
#Expose
private String apiKey;
#SerializedName("Whether_Latest_Version")
#Expose
private Boolean whetherLatestVersion;
#SerializedName("SocketIO_Data")
#Expose
private SocketIOData socketIOData;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Integer getEnvType() {
return envType;
}
public void setEnvType(Integer envType) {
this.envType = envType;
}
public String getApiKey() {
return apiKey;
}
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
public Boolean getWhetherLatestVersion() {
return whetherLatestVersion;
}
public void setWhetherLatestVersion(Boolean whetherLatestVersion) {
this.whetherLatestVersion = whetherLatestVersion;
}
public SocketIOData getSocketIOData() {
return socketIOData;
}
public void setSocketIOData(SocketIOData socketIOData) {
this.socketIOData = socketIOData;
}
#SerializedName("code")
#Expose
private Integer code;
#SerializedName("msg")
#Expose
private String msg;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
public class SocketIOData {
#SerializedName("socket_host")
#Expose
private String socketHost;
#SerializedName("socketjs_link")
#Expose
private String socketjsLink;
public String getSocketHost() {
return socketHost;
}
public void setSocketHost(String socketHost) {
this.socketHost = socketHost;
}
public String getSocketjsLink() {
return socketjsLink;
}
public void setSocketjsLink(String socketjsLink) {
this.socketjsLink = socketjsLink;
}
}
}
Next In My Main Activity I made these changes
public void SplashScreen(SplashRequest splashRequest){
UserService userService = ApiClient.getRetrofit().create(UserService.class);
Call<SplashResponse> splashResponseCall = userService.splashScreen(splashRequest);
splashResponseCall.enqueue(new Callback<SplashResponse>() {
#Override
public void onResponse(Call<SplashResponse> call, Response<SplashResponse> response) {
Gson gson = new Gson();
String successResponse = gson.toJson(response.body());
SplashResponse response1 = response.body();
if (response.isSuccessful()) {
Toast.makeText(MainActivity.this, response1.getExtras().getStatus(), Toast.LENGTH_LONG).show();
}else {
//Toast.makeText(MainActivity.this, response1.getExtras().getStatus(), Toast.LENGTH_LONG).show();
if(response1.getExtras().getCode() == 1){
Toast.makeText(MainActivity.this, response1.getExtras().getMsg(), Toast.LENGTH_LONG).show();
}else{
Toast.makeText(MainActivity.this, response1.getExtras().getMsg(), Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onFailure(Call<SplashResponse> call, Throwable t) {
String msg = t.getLocalizedMessage();
Toast.makeText(MainActivity.this,msg,Toast.LENGTH_SHORT).show();
}
});
}
This is my json data
{
"Success": true,
"Message": "User Not Found",
"Customer_Data": "",
"Customer_Device": "",
"Customer_Event": "",
"All_Event": [
{
"event_id": 6,
"event_name": "Test Event - 1",
"start_date": "01/06/2019",
"end_date": "01/06/2019",
"address_1": "Mumbai",
"address_2": "Mumbai",
"location_link": "https://goo.gl/maps/vTia6DQxwmiA5kvz6",
"pincode": 400060,
"state_id": 10,
"city_id": 355,
"sechudel": "Test",
"itinerary": "Test",
"edate": "2019-05-09T17:00:05.95592",
"eventimg": "http://zaidicorp.in/login/ProcessImage/636935218388448729.png"
}
],
"Status": 1,
"Currentdate": "5/16/2019 11:40:54 AM"
}
this is my pojo file
package mytraining.com.mytraining.Pojo;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
import java.util.List;
public class OtpCheck implements Serializable {
#SerializedName("Success")
#Expose
private Boolean success;
#SerializedName("Message")
#Expose
private String message;
#SerializedName("Customer_Data")
#Expose
private List<CustomerData> customerData;
#SerializedName("Customer_Device")
#Expose
private List<CustomerDevice> customerDevice;
#SerializedName("Customer_Event")
#Expose
private List<CustomerEvent> customerEvent;
#SerializedName("Event")
#Expose
private List<EventDetail> eventDetails;
#SerializedName("Status")
#Expose
private Integer status;
#SerializedName("Currentdate")
#Expose
private String currentdate;
public List<EventDetail> getEventDetails() {
return eventDetails;
}
public void setEventDetails(List<EventDetail> eventDetails) {
this.eventDetails = eventDetails;
}
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<CustomerData> getCustomerData() {
return customerData;
}
public void setCustomerData(List<CustomerData> customerData) {
this.customerData = customerData;
}
public List<CustomerDevice> getCustomerDevice() {
return customerDevice;
}
public void setCustomerDevice(List<CustomerDevice> customerDevice) {
this.customerDevice = customerDevice;
}
public List<CustomerEvent> getCustomerEvent() {
return customerEvent;
}
public void setCustomerEvent(List<CustomerEvent> customerEvent) {
this.customerEvent = customerEvent;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getCurrentdate() {
return currentdate;
}
public void setCurrentdate(String currentdate) {
this.currentdate = currentdate;
}
/**
* Inner Class For Customer Data
*/
public static class CustomerData implements Serializable {
#SerializedName("cust_id")
#Expose
private Integer custId;
#SerializedName("cust_email")
#Expose
private String custEmail;
#SerializedName("customername")
#Expose
private String customername;
#SerializedName("personalcontact")
#Expose
private String personalcontact;
public Integer getCustId() {
return custId;
}
public void setCustId(Integer custId) {
this.custId = custId;
}
public String getCustEmail() {
return custEmail;
}
public void setCustEmail(String custEmail) {
this.custEmail = custEmail;
}
public String getCustomername() {
return customername;
}
public void setCustomername(String customername) {
this.customername = customername;
}
public String getPersonalcontact() {
return personalcontact;
}
public void setPersonalcontact(String personalcontact) {
this.personalcontact = personalcontact;
}
}
/**
* Inner Class For Customer Device
*/
public static class CustomerDevice implements Serializable {
#SerializedName("cust_id")
#Expose
private Integer custId;
#SerializedName("Cust_device")
#Expose
private String custDevice;
#SerializedName("bg_device_Brand")
#Expose
private String bgDeviceBrand;
#SerializedName("bg_device_model")
#Expose
private String bgDeviceModel;
#SerializedName("android_ver")
#Expose
private String androidVer;
#SerializedName("device_mac")
#Expose
private String deviceMac;
#SerializedName("opt")
#Expose
private Object opt;
public Integer getCustId() {
return custId;
}
public void setCustId(Integer custId) {
this.custId = custId;
}
public String getCustDevice() {
return custDevice;
}
public void setCustDevice(String custDevice) {
this.custDevice = custDevice;
}
public String getBgDeviceBrand() {
return bgDeviceBrand;
}
public void setBgDeviceBrand(String bgDeviceBrand) {
this.bgDeviceBrand = bgDeviceBrand;
}
public String getBgDeviceModel() {
return bgDeviceModel;
}
public void setBgDeviceModel(String bgDeviceModel) {
this.bgDeviceModel = bgDeviceModel;
}
public String getAndroidVer() {
return androidVer;
}
public void setAndroidVer(String androidVer) {
this.androidVer = androidVer;
}
public String getDeviceMac() {
return deviceMac;
}
public void setDeviceMac(String deviceMac) {
this.deviceMac = deviceMac;
}
public Object getOpt() {
return opt;
}
public void setOpt(Object opt) {
this.opt = opt;
}
}
/**
* Inner Class For Customer Event
*/
public static class CustomerEvent implements Serializable {
#SerializedName("ticket_no")
#Expose
private String ticketNo;
#SerializedName("seat_no")
#Expose
private String seatNo;
#SerializedName("event_name")
#Expose
private String eventName;
#SerializedName("start_date")
#Expose
private String startDate;
#SerializedName("end_date")
#Expose
private String endDate;
#SerializedName("location_link")
#Expose
private String locationLink;
#SerializedName("edate")
#Expose
private String edate;
public String getTicketNo() {
return ticketNo;
}
public void setTicketNo(String ticketNo) {
this.ticketNo = ticketNo;
}
public String getSeatNo() {
return seatNo;
}
public void setSeatNo(String seatNo) {
this.seatNo = seatNo;
}
public String getEventName() {
return eventName;
}
public void setEventName(String eventName) {
this.eventName = eventName;
}
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 String getLocationLink() {
return locationLink;
}
public void setLocationLink(String locationLink) {
this.locationLink = locationLink;
}
public String getEdate() {
return edate;
}
public void setEdate(String edate) {
this.edate = edate;
}
}
/**
* Inner Class For Event Detail
*/
public static class EventDetail implements Serializable {
#SerializedName("event_id")
#Expose
private Integer eventId;
#SerializedName("event_name")
#Expose
private String eventName;
#SerializedName("start_date")
#Expose
private String startDate;
#SerializedName("end_date")
#Expose
private String endDate;
#SerializedName("address_1")
#Expose
private String address1;
#SerializedName("address_2")
#Expose
private String address2;
#SerializedName("location_link")
#Expose
private String locationLink;
#SerializedName("pincode")
#Expose
private Integer pincode;
#SerializedName("state_id")
#Expose
private Integer stateId;
#SerializedName("city_id")
#Expose
private Integer cityId;
#SerializedName("sechudel")
#Expose
private String sechudel;
#SerializedName("itinerary")
#Expose
private String itinerary;
#SerializedName("edate")
#Expose
private String edate;
#SerializedName("eventimg")
#Expose
private String eventimg;
public Integer getEventId() {
return eventId;
}
public void setEventId(Integer eventId) {
this.eventId = eventId;
}
public String getEventName() {
return eventName;
}
public void setEventName(String eventName) {
this.eventName = eventName;
}
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 String getAddress1() {
return address1;
}
public void setAddress1(String address1) {
this.address1 = address1;
}
public String getAddress2() {
return address2;
}
public void setAddress2(String address2) {
this.address2 = address2;
}
public String getLocationLink() {
return locationLink;
}
public void setLocationLink(String locationLink) {
this.locationLink = locationLink;
}
public Integer getPincode() {
return pincode;
}
public void setPincode(Integer pincode) {
this.pincode = pincode;
}
public Integer getStateId() {
return stateId;
}
public void setStateId(Integer stateId) {
this.stateId = stateId;
}
public Integer getCityId() {
return cityId;
}
public void setCityId(Integer cityId) {
this.cityId = cityId;
}
public String getSechudel() {
return sechudel;
}
public void setSechudel(String sechudel) {
this.sechudel = sechudel;
}
public String getItinerary() {
return itinerary;
}
public void setItinerary(String itinerary) {
this.itinerary = itinerary;
}
public String getEdate() {
return edate;
}
public void setEdate(String edate) {
this.edate = edate;
}
public String getEventimg() {
return eventimg;
}
public void setEventimg(String eventimg) {
this.eventimg = eventimg;
}
}
}
this my is java calling class
private void eventDetial(Map<String, String> map) {
Call<OtpCheck> call = apiInterface.eventShow(map);
call.enqueue(new Callback<OtpCheck>() {
#Override
public void onResponse(Call<OtpCheck> call, Response<OtpCheck> response) {
List<OtpCheck.EventDetail> data = response.body().getEventDetails();
for (int i = 0; i < 1; i++) {
image = data.get(i).getEventimg();
Log.i("Data", "data");
Glide.with(getActivity()).load(image).into(imageView);
}
}
#Override
public void onFailure(Call<OtpCheck> call, Throwable t) {
Toast.makeText(getContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
I tried multiple ways from StackOverflow but still not getting error
expected begin_array but was String
Firstly got Error from below field, this 3 field is String but you set ArrayList. But it will be String. Like below.
"Customer_Data": "",
"Customer_Device": "",
"Customer_Event": "",
#SerializedName("Customer_Data")
#Expose
private String customerData;
#SerializedName("Customer_Device")
#Expose
private String customerDevice;
#SerializedName("Customer_Event")
#Expose
private String customerEvent;
Also, Have no any event field. so need change from
#SerializedName("Event")
#Expose
private List<EventDetail> eventDetails;
To
#SerializedName("All_Event")
#Expose
private List<EventDetail> eventDetails;
Your problem is in your #SerializedName:
#SerializedName("Event")
#Expose
private List<EventDetail> eventDetails;
The tag SerializedName must have the name of the element of the json. Then you must changue it for:
#SerializedName("All_Event")
#Expose
private List<EventDetail> eventDetails;
I'm a new android developer.. So I have a problem this.. I'm parsing nested json data with gson but return null varaible. Please help me.!
My json Data is:
{"result":"success","data":{"Items":[{"id":"5b7c8950-692a-11e6-a3c9-03b4285ed321","accountName":"5b7c8950-692a-11e6-a3c9-03b4285ed321#finanskutusu.com","userId":"111903139847063022019"}],"Count":1,"ScannedCount":12}}
AccountModel.java :
public class AccountModel {
private String result;
public Data data;
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}}
Data.java :
public class Data {
public Items[] Items;
private String Count;
private String ScannedCount;
public Items[] getItems() {
return Items;
}
public void setItems(Items[] Items) {
this.Items = Items;
}
public String getCount() {
return Count;
}
public void setCount(String Count) {
this.Count = Count;
}
public String getScannedCount() {
return ScannedCount;
}
public void setScannedCount(String ScannedCount) {
this.ScannedCount = ScannedCount;
}}
Items.java :
public class Items {
private String id;
private String accountName;
private String userId;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}}
Thanks..
I have parsed the data successfully using the model classes provided (no changes). Here is the parser program,
Gson gson = new GsonBuilder().create();
AccountModel am = gson.fromJson("{\"result\":\"success\",\"data\": {\"Items\":[{\"id\":\"5b7c8950-692a-11e6-a3c9- 03b4285ed321\",\"accountName\":\"5b7c8950-692a-11e6-a3c9-03b4285ed321#finanskutusu.com\",\"userId\":\"111903139847063022019\"}],\"Count\":1,\"ScannedCount\":12}}", AccountModel.class);
System.out.println(am.getResult());
System.out.println(am.getData().getCount());
Items i[] = am.getData().getItems();
System.out.println(i[0].getAccountName());
Output
success
1
5b7c8950-692a-11e6-a3c9-03b4285ed321#finanskutusu.com
This question already has an answer here:
How to convert JSONArray to List with Gson?
(1 answer)
Closed 6 years ago.
How to convert a jsonArray with multiple jsonObjects to an arraylist using Gson.
Here is my Json String:
[{"AccommoAddress":{
"PostalCode":2109,
"Street":"22 Ararat Str",
"Town":"Westdene"
},
"AccommoDetails":{
"AccommoId":0,
"CleaningService":1,
"DSTV":1,
"DedicatedStudyArea":1
},
"AccommoID":1,
"AccommoMainImage":{
"CategoryId":0,
"ContentType":".png",
"DateUploaded":"2016-07-16",
"FileSize":2362,
"ImageCategory":"MAIN",
"ImageId":1,
"ImageName":"images.png"
}]
First , it's not a correct Json format.
"ImageName":"images.png" <- (you need to put a "}" here )
Second , create a entity
public class TargetEntity {
private AccommoAddressEntity AccommoAddress;
private AccommoDetailsEntity AccommoDetails;
private int AccommoID;
private AccommoMainImageEntity AccommoMainImage;
public AccommoAddressEntity getAccommoAddress() {
return AccommoAddress;
}
public void setAccommoAddress(AccommoAddressEntity AccommoAddress) {
this.AccommoAddress = AccommoAddress;
}
public AccommoDetailsEntity getAccommoDetails() {
return AccommoDetails;
}
public void setAccommoDetails(AccommoDetailsEntity AccommoDetails) {
this.AccommoDetails = AccommoDetails;
}
public int getAccommoID() {
return AccommoID;
}
public void setAccommoID(int AccommoID) {
this.AccommoID = AccommoID;
}
public AccommoMainImageEntity getAccommoMainImage() {
return AccommoMainImage;
}
public void setAccommoMainImage(AccommoMainImageEntity AccommoMainImage) {
this.AccommoMainImage = AccommoMainImage;
}
public static class AccommoAddressEntity {
private int PostalCode;
private String Street;
private String Town;
public int getPostalCode() {
return PostalCode;
}
public void setPostalCode(int PostalCode) {
this.PostalCode = PostalCode;
}
public String getStreet() {
return Street;
}
public void setStreet(String Street) {
this.Street = Street;
}
public String getTown() {
return Town;
}
public void setTown(String Town) {
this.Town = Town;
}
}
public static class AccommoDetailsEntity {
private int AccommoId;
private int CleaningService;
private int DSTV;
private int DedicatedStudyArea;
public int getAccommoId() {
return AccommoId;
}
public void setAccommoId(int AccommoId) {
this.AccommoId = AccommoId;
}
public int getCleaningService() {
return CleaningService;
}
public void setCleaningService(int CleaningService) {
this.CleaningService = CleaningService;
}
public int getDSTV() {
return DSTV;
}
public void setDSTV(int DSTV) {
this.DSTV = DSTV;
}
public int getDedicatedStudyArea() {
return DedicatedStudyArea;
}
public void setDedicatedStudyArea(int DedicatedStudyArea) {
this.DedicatedStudyArea = DedicatedStudyArea;
}
}
public static class AccommoMainImageEntity {
private int CategoryId;
private String ContentType;
private String DateUploaded;
private int FileSize;
private String ImageCategory;
private int ImageId;
private String ImageName;
public int getCategoryId() {
return CategoryId;
}
public void setCategoryId(int CategoryId) {
this.CategoryId = CategoryId;
}
public String getContentType() {
return ContentType;
}
public void setContentType(String ContentType) {
this.ContentType = ContentType;
}
public String getDateUploaded() {
return DateUploaded;
}
public void setDateUploaded(String DateUploaded) {
this.DateUploaded = DateUploaded;
}
public int getFileSize() {
return FileSize;
}
public void setFileSize(int FileSize) {
this.FileSize = FileSize;
}
public String getImageCategory() {
return ImageCategory;
}
public void setImageCategory(String ImageCategory) {
this.ImageCategory = ImageCategory;
}
public int getImageId() {
return ImageId;
}
public void setImageId(int ImageId) {
this.ImageId = ImageId;
}
public String getImageName() {
return ImageName;
}
public void setImageName(String ImageName) {
this.ImageName = ImageName;
}
}
}
Third
Gson gson = new Gson();
TargetEntity[] target = gson.fromJson(JsonString,TargetEntity[].class)
java object: MyObject has a list of AnotherObject1 and AnotherObject1 also have a list of AnotherObject2
class MyObject{
private String status;
private String message;
private List<AnotherObject1> data;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<AnotherObject1> getData() {
return data;
}
public void setData(List<AnotherObject1> data) {
this.data = data;
}
}
Class AnotherObject1{
private Integer group_id;
private List<AnotherObject2> anotherList;
public Integer getGroup_id() {
return group_id;
}
public void setGroup_id(Integer group_id) {
this.group_id = group_id;
}
public List<AnotherObject2> getAnotherList() {
return smsList;
}
public void setAnotherList(List<AnotherObject2> anotherList) {
this.anotherList = anotherList;
}
}
class AnotherObject2{
private String customid;
private String customid1 ;
private Long mobile;
private String status;
private String country;
public String getCustomid() {
return customid;
}
public void setCustomid(String customid) {
this.customid = customid;
}
public String getCustomid1() {
return customid1;
}
public void setCustomid1(String customid1) {
this.customid1 = customid1;
}
public Long getMobile() {
return mobile;
}
public void setMobile(Long mobile) {
this.mobile = mobile;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
JSON String: this is my json string by which i want to make an java object using object mapper
String response="{\"status\":\"OK\",\"data\":{\"group_id\":39545922,\"0\":{\"id\":\"39545922-1\",\"customid\":\"\",\"customid1\":\"\",\"customid2\":\"\",\"mobile\":\"910123456789\",\"status\":\"XYZ\",\"country\":\"IN\"}},\"message\":\"WE R Happy.\"}"
ObjectMapper code
//convert string to response object
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
objectMapper.readValue(responseBody, MyObject.class);
exception: here is the exception
com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token
at [Source: {"status":"OK","data":{"group_id":39545922,"0":{"id":"39545922-1","customid":"","customid1":"","customid2":"","mobile":"910123456789","status":"GOOD","country":"IN"}},"message":"We R happy."}; line: 1, column: 15] (through reference chain: MyObject["data"])
at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:148)
at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:854)
at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:850)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.handleNonArray(CollectionDeserializer.java:292)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:227)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:217)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:25)
at com.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:520)
at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:95)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:256)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:125)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3702)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2714)
at abc.disp(RestClientImpl.java:210)
at abc.disp(RestClientImpl.java:105)
at Application.<init>(Application.java:42)
at Application.main(Application.java:45)
please guide me how to make it possible.
Your code itself is not compailable ...
private List<AnotherObject1> data; // Your class member is list of AnotherObject1
and below it is used as List of SMSDTO in getter and setter
public List<SMSDTO> getData() {
return data;
}
Problem is quite simple: you claim data should become Java List; and this requires that JSON input for it should be JSON Array. But what JSON instead has is a JSON Object.
So you either need to change POJO definition to expect something compatible with JSON Object (a POJO or java.util.Map); or JSON to contain an array for data.
First as Naveen Ramawat said your code is not compilable as it is.
In the class AnotherObject1 getSmsList should take AnotherObject2 and setSmsList should take AnotherObject2 also as parameter.
In the class MyObject setData and getData should use AnotherObject1 as parameters
Second your JSON string is not valid it should be sommething like that:
{"status":"OK","data":[{"group_id":39545922,"smsList":[{"customid":"39545922-1","customid1":"","mobile":913456789,"status":"XYZ","country":"XYZ"}]}]}
Here is the code that I used :
MyObject.java:
import java.util.List;
class MyObject {
private String status;
private String message;
private List<AnotherObject1> data;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<AnotherObject1> getData() {
return data;
}
public void setData(List<AnotherObject1> data) {
this.data = data;
}
}
AnotherObject1.java :
import java.util.List;
public class AnotherObject1 {
private Integer group_id;
private List<AnotherObject2> smsList;
public Integer getGroup_id() {
return group_id;
}
public void setGroup_id(Integer group_id) {
this.group_id = group_id;
}
public List<AnotherObject2> getSmsList() {
return smsList;
}
public void setSmsList(List<AnotherObject2> smsList) {
this.smsList = smsList;
}
}
AnotherObject2.java :
public class AnotherObject2 {
private String customid;
private String customid1;
private Long mobile;
private String status;
private String country;
public String getCustomid() {
return customid;
}
public void setCustomid(String customid) {
this.customid = customid;
}
public String getCustomid1() {
return customid1;
}
public void setCustomid1(String customid1) {
this.customid1 = customid1;
}
public Long getMobile() {
return mobile;
}
public void setMobile(Long mobile) {
this.mobile = mobile;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
To get the JSON string :
import org.json.JSONObject;
import org.json.XML;
import com.google.gson.Gson;
MyObject myObj = new MyObject();
ArrayList<AnotherObject2> smsList = new ArrayList<AnotherObject2>();
ArrayList<AnotherObject1> data = new ArrayList<AnotherObject1>();
AnotherObject1 ao1 = new AnotherObject1();
ao1.setGroup_id(39545922);
ao1.setSmsList(smsList);
AnotherObject2 sms = new AnotherObject2();
sms.setCountry("XYZ");
sms.setCustomid("39545922-1");
sms.setCustomid1("");
sms.setMobile((long) 913456789);
sms.setStatus("XYZ");
smsList.add(sms);
ao1.setSmsList(smsList);
data.add(ao1);
myObj.setStatus("OK");
myObj.setData(data);
// Build a JSON string to display
Gson gson = new Gson();
String jsonString = gson.toJson(myObj);
System.out.println(jsonString);
// Get an object from a JSON string
MyObject myObject2 = gson.fromJson(jsonString, MyObject.class);
// Display the new object
System.out.println(gson.toJson(myObject2));