Fetching Nested JSON Arrays with retrofit? - java

I searched a lot in Google to find a way to use Nested Json Arrays with Retrofit, but it is useless
Most of what I found talks about using JSON Objects with retrofit
And my main issue is how to use the nested Array list inside call method to get data from the server
I have this
JSON
{
"orders": [
{
"ID": "1",
"OrderDate": "2020-07-01",
"order_details": [
{
"detail_ID": "1",
"description": "new order",
"items": [
{
"item_ID": "1",
"item_name": "milk",
"Quantity": "4",
"Price": "56.0",
"UnitOfMeasure": "unit"
},
{
"item_ID": "1",
"item_name": "nuts",
"Quantity": "6",
"Price": "500",
"UnitOfMeasure": "unit"
}
]
}
]
}
]
}
And those my other classes
Item.java
public class Item {
#SerializedName("item_ID")
#Expose
private String itemID;
#SerializedName("item_name")
#Expose
private String itemName;
#SerializedName("Quantity")
#Expose
private String quantity;
#SerializedName("Price")
#Expose
private String price;
#SerializedName("UnitOfMeasure")
#Expose
private String unit_Of_Measure;
public String getItemID() {
return itemID;
}
public void setItemID(String itemID) {
this.itemID = itemID;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getUnitOfMeasure() {
return unitOfMeasure;
}
public void setUnitOfMeasure(String unitOfMeasure) {
this.unitOfMeasure = unitOfMeasure;
}
}
Order.java
public class Order {
#SerializedName("orders")
#Expose
private List<Order_> orders = null;
public List<Order_> getOrders() {
return orders;
}
public void setOrders(List<Order_> orders) {
this.orders = orders;
}
}
OrderDetail.java
public class OrderDetail {
#SerializedName("detail_ID")
#Expose
private String detailID;
#SerializedName("description")
#Expose
private String description;
#SerializedName("items")
#Expose
private List<Item> items = null;
public String getDetailID() {
return detailID;
}
public void setDetailID(String detailID) {
this.detailID = detailID;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
}
Order_.java
public class Order_ {
#SerializedName("ID")
#Expose
private String iD;
#SerializedName("OrderDate")
#Expose
private String orderDate;
#SerializedName("order_details")
#Expose
private List<OrderDetail> orderDetails = null;
public String getID() {
return iD;
}
public void setID(String iD) {
this.iD = iD;
}
public String getOrderDate() {
return orderDate;
}
public void setOrderDate(String orderDate) {
this.orderDate = orderDate;
}
public List<OrderDetail> getOrderDetails() {
return orderDetails;
}
public void setOrderDetails(List<OrderDetail> orderDetails) {
this.orderDetails = orderDetails;
}
}
ApiInterface.java
#GET("orders")
Call<Order> getAllOrders();
Now I want to get order_detail, item data inside this function
order.enqueue(new Callback<Order>() {
#Override
public void onResponse(Call<Order> call, Response<Order> response) {
if(response.isSuccessful()){
//here ..................
}
}
#Override
public void onFailure(Call<TaskResponse> call, Throwable t) {
Log.w(TAG, "onFailure: " + t.getMessage());
}
});
I will be so grateful who can help me

Related

Json error for Java with Gson and retrofit [Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 70 path $.Data]

I am consuming an API about cryptocurrency news called CryptoCompare.
My problem is that I can't detect what my code error is.
The error is as follows -> com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 70 path $.Data
I copy the Json and my two classes to help me find the solution.
Json:
{
"Type": 100,
"Message": "News list successfully returned",
"Promoted": [
],
"Data": [
{
"id": "2940487",
"guid": "https://cointelegraph.com/news/australian-hacker-pleads-guilty-to-stealing-450-000-in-xrp-last-year",
"published_on": 1566590880,
"imageurl": "https://images.cryptocompare.com/news/cointelegraph/dj0O90McM86.png",
"title": "Australian Hacker Pleads Guilty to Stealing $450,000 in XRP Last Year",
"url": "https://cointelegraph.com/news/australian-hacker-pleads-guilty-to-stealing-450-000-in-xrp-last-year",
"source": "cointelegraph",
"body": "An Australian woman has pleaded guilty to stealing $450,000 in XRP",
"tags": "Altcoin|Australia|Fraud|Hackers|XRP|Tokens|Police",
"categories": "XRP|ICO|Altcoin",
"upvotes": "0",
"downvotes": "0",
"lang": "EN",
"source_info": {
"name": "CoinTelegraph",
"lang": "EN",
"img": "https://images.cryptocompare.com/news/default/cointelegraph.png"
}
},
]
Link of Api -> https://min-api.cryptocompare.com/data/v2/news/?lang=EN
Java Class News:
public class News {
#SerializedName("Type")
#Expose
private Integer type;
#SerializedName("Message")
#Expose
private String message;
#SerializedName("Data")
#Expose
private List<Article> articles = null;
#SerializedName("HasWarning")
#Expose
private Boolean hasWarning;
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<Article> getArticles() {
return articles;
}
public void setArticles(List<Article> articles) {
this.articles = articles;
}
public Boolean getHasWarning() {
return hasWarning;
}
public void setHasWarning(Boolean hasWarning) {
this.hasWarning = hasWarning;
}
Java Class Article:
public class Article {
#SerializedName("id")
#Expose
private String id;
#SerializedName("guid")
#Expose
private String guid;
#SerializedName("published_on")
#Expose
private Integer publishedOn;
#SerializedName("imageurl")
#Expose
private String imageurl;
#SerializedName("title")
#Expose
private String title;
#SerializedName("url")
#Expose
private String url;
#SerializedName("source")
#Expose
private String source;
#SerializedName("body")
#Expose
private String body;
#SerializedName("tags")
#Expose
private String tags;
#SerializedName("categories")
#Expose
private String categories;
#SerializedName("upvotes")
#Expose
private String upvotes;
#SerializedName("downvotes")
#Expose
private String downvotes;
#SerializedName("lang")
#Expose
private String lang;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getGuid() {
return guid;
}
public void setGuid(String guid) {
this.guid = guid;
}
public Integer getPublishedOn() {
return publishedOn;
}
public void setPublishedOn(Integer publishedOn) {
this.publishedOn = publishedOn;
}
public String getImageurl() {
return imageurl;
}
public void setImageurl(String imageurl) {
this.imageurl = imageurl;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getTags() {
return tags;
}
public void setTags(String tags) {
this.tags = tags;
}
public String getCategories() {
return categories;
}
public void setCategories(String categories) {
this.categories = categories;
}
public String getUpvotes() {
return upvotes;
}
public void setUpvotes(String upvotes) {
this.upvotes = upvotes;
}
public String getDownvotes() {
return downvotes;
}
public void setDownvotes(String downvotes) {
this.downvotes = downvotes;
}
public String getLang() {
return lang;
}
public void setLang(String lang) {
this.lang = lang;
}
}
Interface to call Api:
public interface ApiInterface {
#GET("news")
Call<News> getNews(
#Query("lang") String lang,
#Query("api_key") String apiKey,
#Query("lTs") int lTs
);
Retrofit Class Builder
public static Retrofit getApiClient(String BASE_URL){
retrofit = new Retrofit.Builder().baseUrl(BASE_URL)
.client(getUnsafeOkHttpClient().build())
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit;
}
Fragment of Code when i call the api
private void LoadJson(){
swipeRefreshLayout.setRefreshing(true);
final ApiInterface apiInterface = ApiClient.getApiClient(ApiUtils.BASE_URL_NEWS).create(ApiInterface.class);
Call<News> call;
call = apiInterface.getNews("EN", ApiUtils.API_KEY,0);
call.enqueue(new Callback<News>() {
#Override
public void onResponse(Call<News> call, Response<News> response) {
if (response.isSuccessful() && response.body() != null){
articles.addAll(response.body().getArticles());
if (articles.size() - response.body().getArticles().size() == 0){
adapterNews.notifyDataSetChanged();
} else {
adapterNews.notifyItemRangeInserted(articles.size() - response.body().getArticles().size(), response.body().getArticles().size());
}
swipeRefreshLayout.setRefreshing(false);
progressBar.setVisibility(View.GONE);
} else {
Toast.makeText(getContext(), "No result", Toast.LENGTH_SHORT).show();
swipeRefreshLayout.setRefreshing(false);
progressBar.setVisibility(View.GONE);
}
}
#Override
public void onFailure(Call<News> call, Throwable t) {
Log.e(TAG, "ERROR API: " + t.getMessage() + " - " + t.getCause());
}
});
}
Any contribution is very helpful.
Thank you
FIXED THE PROBLEM WAS IN THE CALL
I notice that when you try query on api with wrong value like this
https://min-api.cryptocompare.com/data/v2/news/?lang=en
gives you json instead of array for data so this produce error
For fix and test instead of Locale.getDefault().getLanguage() use just "EN" and check the result
also for more help you can use this logging-interceptor

JsonIllegalstateexception:- Expected BEGIN_ARRAY but was String at line 1 column 61 . $ customer.Data

There is JSON file and i want get through POJO so i Created POJO file as well but at customer data it show in some error like i mention in title i don't know what's happening i mean my whole team don't why it's happening.
I've try everything which i would try but nothing is helping me out
{
"Success": true,
"Message": "Device Not Found",
"Customer_Data": [{
"customerid": 12365,
"customername": "Mukesh SHARMA",
"gender": "M",
"personalcontact": 999999999,
"homecontact": 999999999,
"emailid": "mukeshr334#gmail.com",
"address": "RockStar",
"designation": "Chief Life Insurance Advisor",
"stateid": 22,
"statename": "Uttar Pradesh",
"cityid": 557,
"cityname": "Sant Ravidas Nagar",
"pincode": 221304,
"birthdate": "14-11-1983",
"marriagedate": "2018-01-01",
"category": "-- Select --",
"mdrttick": false,
"profilepicture": "http://mdddddddtaupdate.in/profile_pic/12365.jpg",
"branchname": "ModelTown",
"branchcode": "123",
"licbranchid": 20596,
"division": "Delhi DO-II",
"licdivisionentryid": 51,
"password": "123456",
"employeename": "Shahnawaz Khan",
"empcontact": 999999999,
"empmail": "shane_madddian#yahoo.com",
"dealername": "Sachinder",
"deacontact": 999999999,
"deamail": "ddd#gamil.com",
"club_member": "-- Select --",
"lifeinsurance": false,
"nonlife": false,
"healthinsurance": false,
"mutualfunds": false,
"other": false,
"efrom": "A",
"edate": "2019-05-09 13:03:17.63214",
"website": "",
"maxdate": "01-01-2000 00:00:00"
}],
"Customer_Device": "",
"Customer_Event": "",
"All_Event": [{
"event_id": 6,
"event_name": "Test Event - 1",
"start_date": "01/06/2019",
"end_date": "02/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": 2,
"Currentdate": "5/18/2019"
}
This is my 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 = null;
#SerializedName("Customer_Device")
#Expose
private String customerDevice;
#SerializedName("Customer_Event")
#Expose
private String customerEvent;
#SerializedName("All_Event")
#Expose
private List<EventDetail> getEventDetails = null;
#SerializedName("Status")
#Expose
private Integer status;
#SerializedName("Currentdate")
#Expose
private String currentdate;
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 String getCustomerDevice() {
return customerDevice;
}
public void setCustomerDevice(String customerDevice) {
this.customerDevice = customerDevice;
}
public String getCustomerEvent() {
return customerEvent;
}
public void setCustomerEvent(String customerEvent) {
this.customerEvent = customerEvent;
}
public List<EventDetail> getEventDetails() {
return getEventDetails;
}
public void setEventDetails(List<EventDetail> getEventDetails) {
this.getEventDetails = getEventDetails;
}
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;
}
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;
}
}
public static class CustomerData implements Serializable {
#SerializedName("customerid")
#Expose
private Integer customerid;
#SerializedName("customername")
#Expose
private String customername;
#SerializedName("gender")
#Expose
private String gender;
#SerializedName("personalcontact")
#Expose
private Integer personalcontact;
#SerializedName("homecontact")
#Expose
private Integer homecontact;
#SerializedName("emailid")
#Expose
private String emailid;
#SerializedName("address")
#Expose
private String address;
#SerializedName("designation")
#Expose
private String designation;
#SerializedName("stateid")
#Expose
private Integer stateid;
#SerializedName("statename")
#Expose
private String statename;
#SerializedName("cityid")
#Expose
private Integer cityid;
#SerializedName("cityname")
#Expose
private String cityname;
#SerializedName("pincode")
#Expose
private Integer pincode;
#SerializedName("birthdate")
#Expose
private String birthdate;
#SerializedName("marriagedate")
#Expose
private String marriagedate;
#SerializedName("category")
#Expose
private String category;
#SerializedName("mdrttick")
#Expose
private Boolean mdrttick;
#SerializedName("profilepicture")
#Expose
private String profilepicture;
#SerializedName("branchname")
#Expose
private String branchname;
#SerializedName("branchcode")
#Expose
private String branchcode;
#SerializedName("licbranchid")
#Expose
private Integer licbranchid;
#SerializedName("division")
#Expose
private String division;
#SerializedName("licdivisionentryid")
#Expose
private Integer licdivisionentryid;
#SerializedName("password")
#Expose
private String password;
#SerializedName("employeename")
#Expose
private String employeename;
#SerializedName("empcontact")
#Expose
private Integer empcontact;
#SerializedName("empmail")
#Expose
private String empmail;
#SerializedName("dealername")
#Expose
private String dealername;
#SerializedName("deacontact")
#Expose
private Integer deacontact;
#SerializedName("deamail")
#Expose
private String deamail;
#SerializedName("club_member")
#Expose
private String clubMember;
#SerializedName("lifeinsurance")
#Expose
private Boolean lifeinsurance;
#SerializedName("nonlife")
#Expose
private Boolean nonlife;
#SerializedName("healthinsurance")
#Expose
private Boolean healthinsurance;
#SerializedName("mutualfunds")
#Expose
private Boolean mutualfunds;
#SerializedName("other")
#Expose
private Boolean other;
#SerializedName("efrom")
#Expose
private String efrom;
#SerializedName("edate")
#Expose
private String edate;
#SerializedName("website")
#Expose
private String website;
#SerializedName("maxdate")
#Expose
private String maxdate;
public Integer getCustomerid() {
return customerid;
}
public void setCustomerid(Integer customerid) {
this.customerid = customerid;
}
public String getCustomername() {
return customername;
}
public void setCustomername(String customername) {
this.customername = customername;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Integer getPersonalcontact() {
return personalcontact;
}
public void setPersonalcontact(Integer personalcontact) {
this.personalcontact = personalcontact;
}
public Integer getHomecontact() {
return homecontact;
}
public void setHomecontact(Integer homecontact) {
this.homecontact = homecontact;
}
public String getEmailid() {
return emailid;
}
public void setEmailid(String emailid) {
this.emailid = emailid;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public Integer getStateid() {
return stateid;
}
public void setStateid(Integer stateid) {
this.stateid = stateid;
}
public String getStatename() {
return statename;
}
public void setStatename(String statename) {
this.statename = statename;
}
public Integer getCityid() {
return cityid;
}
public void setCityid(Integer cityid) {
this.cityid = cityid;
}
public String getCityname() {
return cityname;
}
public void setCityname(String cityname) {
this.cityname = cityname;
}
public Integer getPincode() {
return pincode;
}
public void setPincode(Integer pincode) {
this.pincode = pincode;
}
public String getBirthdate() {
return birthdate;
}
public void setBirthdate(String birthdate) {
this.birthdate = birthdate;
}
public String getMarriagedate() {
return marriagedate;
}
public void setMarriagedate(String marriagedate) {
this.marriagedate = marriagedate;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public Boolean getMdrttick() {
return mdrttick;
}
public void setMdrttick(Boolean mdrttick) {
this.mdrttick = mdrttick;
}
public String getProfilepicture() {
return profilepicture;
}
public void setProfilepicture(String profilepicture) {
this.profilepicture = profilepicture;
}
public String getBranchname() {
return branchname;
}
public void setBranchname(String branchname) {
this.branchname = branchname;
}
public String getBranchcode() {
return branchcode;
}
public void setBranchcode(String branchcode) {
this.branchcode = branchcode;
}
public Integer getLicbranchid() {
return licbranchid;
}
public void setLicbranchid(Integer licbranchid) {
this.licbranchid = licbranchid;
}
public String getDivision() {
return division;
}
public void setDivision(String division) {
this.division = division;
}
public Integer getLicdivisionentryid() {
return licdivisionentryid;
}
public void setLicdivisionentryid(Integer licdivisionentryid) {
this.licdivisionentryid = licdivisionentryid;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmployeename() {
return employeename;
}
public void setEmployeename(String employeename) {
this.employeename = employeename;
}
public Integer getEmpcontact() {
return empcontact;
}
public void setEmpcontact(Integer empcontact) {
this.empcontact = empcontact;
}
public String getEmpmail() {
return empmail;
}
public void setEmpmail(String empmail) {
this.empmail = empmail;
}
public String getDealername() {
return dealername;
}
public void setDealername(String dealername) {
this.dealername = dealername;
}
public Integer getDeacontact() {
return deacontact;
}
public void setDeacontact(Integer deacontact) {
this.deacontact = deacontact;
}
public String getDeamail() {
return deamail;
}
public void setDeamail(String deamail) {
this.deamail = deamail;
}
public String getClubMember() {
return clubMember;
}
public void setClubMember(String clubMember) {
this.clubMember = clubMember;
}
public Boolean getLifeinsurance() {
return lifeinsurance;
}
public void setLifeinsurance(Boolean lifeinsurance) {
this.lifeinsurance = lifeinsurance;
}
public Boolean getNonlife() {
return nonlife;
}
public void setNonlife(Boolean nonlife) {
this.nonlife = nonlife;
}
public Boolean getHealthinsurance() {
return healthinsurance;
}
public void setHealthinsurance(Boolean healthinsurance) {
this.healthinsurance = healthinsurance;
}
public Boolean getMutualfunds() {
return mutualfunds;
}
public void setMutualfunds(Boolean mutualfunds) {
this.mutualfunds = mutualfunds;
}
public Boolean getOther() {
return other;
}
public void setOther(Boolean other) {
this.other = other;
}
public String getEfrom() {
return efrom;
}
public void setEfrom(String efrom) {
this.efrom = efrom;
}
public String getEdate() {
return edate;
}
public void setEdate(String edate) {
this.edate = edate;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public String getMaxdate() {
return maxdate;
}
public void setMaxdate(String maxdate) {
this.maxdate = maxdate;
}
}
}
Expected BEGIN_ARRAY but was String at line 1 column 61 . $ customer.Data
Customer_Event is Arraylist
#SerializedName("Customer_Event")
#Expose
private List<CustomerEvent> customerEvent = null;
Gson Library expecting the Array first not the Object. there is nothing wrong in your code. but need to modify the JSON Structure here.
Try using this structure :
Note rootArray is starting point/ is used for your reference
rootArray[
// object
{
"Key": value,
"Key": value,
"Key": value
}
// array1
"Customer_Data":[
{
"Key": value,
"Key": value,
"Key": value
}
],
// array 2
"All_Event": [
{
"Key": value,
"Key": value,
"Key": value
}
]
]

Getting Null object in HashMap implementation

Iam trying t get values from a HashMap but when i call him and setText the value i always get Null, let me show the code:
MyValues.class
private List<ItemsBean> items;
public List<ItemsBean> getItems() { return items;}
public void setItems(List<ItemsBean> items) { this.items = items; }
public static class ItemsBean {
private Map<String, leakBean> Gitt;
public Map<String, leakBean> getGitt() { return Gitt;}
public void setGitt(Map<String, leakBean> Gitt) { this.Gitt = Gitt;}
public static class leakBean {
private int id;
private String dev;
public int getId() {return id; }
public String getDev(){return dev;}
public void setId(int id) { this.id = id;}
public void setDev(String dev){this.dev = dev;}
}
I´m using Gson so for get the values and use it for .setText or Toast im trying to access like this:
MyValues object;
txt1.setText(String.valueOf( object.getItems().get(0).getGitt().get("id")));
Here i get null, can someone helpme with this? i just need to access to values, also the items.size(); return 1 and must return 3
here is hte JSON:
{
"id": 1001,
"name": "Super1",
"user": {
"name": "The Super 1"
},
"items": [
{
"987987M7812b163eryrt": {
"id": 1,
"dev": "seed"
},
"90812bn120893juuh": {
"id": 2,
"dev": "none"
},
"981273jn19203nj123rg": {
"id": 3,
"dev": "mine"
}
}
]}
Try with these POJOs:
MyValues.java
public class MyValues {
private int id;
private String name;
private User user;
private List<HashMap<String, ItemsBean>> items;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public List<HashMap<String, ItemsBean>> getItems() {
return items;
}
public void setItems(List<HashMap<String, ItemsBean>> items) {
this.items = items;
}
}
User.java
public class User {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
ItemsBean.java
public class ItemsBean {
private int id;
private String dev;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDev() {
return dev;
}
public void setDev(String dev) {
this.dev = dev;
}
}
You can no access the values like so:
object.getItems().get(0).get("987987M7812b163eryrt").getId();

JSON de-serialization using jackson

I've a JSON which I want to deserialize to java object. I tried but failed to succeed. Really appreciate if somebody help it. I was getting below error.
ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
// Note : vairable 'body' is the JSON string which I've shared below.
RpcResponse rs = mapper.readValue(body, RpcResponse.class);
Exception in thread "main"
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot
deserialize instance of Result out of START_ARRAY token
{
"error": null,
"id": "12345",
"result": {
"inventory": [{
"history": [{
"when": "2012-08-30T07:28:51Z",
"changes": [{
"removed": "",
"added": "1",
"field_name": "qty"
},
{
"removed": "normal",
"added": "major",
"field_name": "popularity"
}],
"id": 474599,
"alias": null
}]
}
}
Here are the java classes
public class RpcResponse {
private String error;
private String id;
private Map<String, Result> result;
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Result getResult() {
return result;
}
public void setResult(Result result) {
this.result = result;
}
}
public class Result {
private Map<String, List<Inventory>> inventory;
public Map<String, List<Inventory>> getBugs() {
return inventory;
}
public void setBugs(Map<String, List<Inventory>> inventory) {
this.inventory = inventory;
}
}
public class Inventory {
private String id;
private String alias;
private Map<String, List<History>> history;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAlias() {
return alias;
}
public void setAlias(String alias) {
this.alias = alias;
}
public Map<String, List<History>> getHistory() {
return history;
}
public void setHistory(Map<String, List<History>> history) {
this.history = history;
}
}
public class History {
private String who;
private String when;
private Map<String, Changes> changes;
public String getWho() {
return who;
}
public void setWho(String who) {
this.who = who;
}
public String getWhen() {
return when;
}
public void setWhen(String when) {
this.when = when;
}
public Map<String, Changes> getChanges() {
return changes;
}
public void setChanges(Map<String, Changes> changes) {
this.changes = changes;
}
}
In RCP Response,
private Map<String, Result> result;
should just be
private Result result;
In Result,
private Map<String, List<Inventory>> inventory;
should be
private List<Inventory> inventory;
and in Inventory,
private Map<String, List<History>> history;
should be
private List<History> history;
In History, Map<String,Changes> should be a Collection<Changes>, etc

How to read json response from retrofit [duplicate]

This question already has answers here:
Retrofit 2: Get JSON from Response body
(14 answers)
Closed 5 years ago.
How to read this response from retrofit and store to java class and access somewhere ??
{
"user": {
"__v": 0,
"updated_at": "2017-11-08T12:07:46.729Z",
"created_at": "2017-11-08T12:07:46.729Z",
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6InRlc3QzIiwidXNlcmlkIjozLCJlbWFpbCI6ImFydWwzQHRlc3QuY29tIiwiYWNjZXNzX2xldmVsIjoiQWRtaW4iLCJfaWQiOiI1YTAyZjM5Mjk5OGM4OTI3MjQxYTQ3N2YiLCJncm91cHMiOlt7ImlkIjoxLCJuYW1lIjoiZGlhbGVyIiwiX2lkIjoiNThiM2JmODI5ZTg2MDFjMDVlNzIxNjI3In1dfQ.VKEt1JoXoL_xfRDrrFK-jVj8zC23j4sqZTT2S3HGMbc",
"username": "test3",
"userid": 3,
"email": "arul3#test.com",
"access_level": "Admin",
"_id": "5a02f392998c8927241a477f",
"groups": [{
"id": 1,
"name": "dialer",
"_id": "58b3bf829e8601c05e721627"
}]
}
}
Create classes from pojo like that then parse to retrofit Convert json response to classes
public class MyPojo{
private User user;
public User getUser ()
{
return user;
}
public void setUser (User user)
{
this.user = user;
}
}
User Class:
public class User{
private String username;
private String updated_at;
private String _id;
private String access_level;
private String email;
private String token;
private String userid;
private String __v;
private String created_at;
private Groups[] groups;
public String getUsername ()
{
return username;
}
public void setUsername (String username)
{
this.username = username;
}
public String getUpdated_at ()
{
return updated_at;
}
public void setUpdated_at (String updated_at)
{
this.updated_at = updated_at;
}
public String get_id ()
{
return _id;
}
public void set_id (String _id)
{
this._id = _id;
}
public String getAccess_level ()
{
return access_level;
}
public void setAccess_level (String access_level)
{
this.access_level = access_level;
}
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;
}
public String getUserid ()
{
return userid;
}
public void setUserid (String userid)
{
this.userid = userid;
}
public String get__v ()
{
return __v;
}
public void set__v (String __v)
{
this.__v = __v;
}
public String getCreated_at ()
{
return created_at;
}
public void setCreated_at (String created_at)
{
this.created_at = created_at;
}
public Groups[] getGroups ()
{
return groups;
}
public void setGroups (Groups[] groups)
{
this.groups = groups;
}
}
Groups Class:
public class Groups{
private String id;
private String _id;
private String name;
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
public String get_id ()
{
return _id;
}
public void set_id (String _id)
{
this._id = _id;
}
public String getName ()
{
return name;
}
public void setName (String name)
{
this.name = name;
}}
Now follow that put your classes and get desire response Retrofit Json response

Categories