How to convert this nested json string to a java object? - java

I have the following JSON string in a "special" format.
I want to convert it to an object in java but I don't know how to access single values for example the value of location or "resolved_at".
I tried with GSON and JSONPOBJECT but it doesn't work with this one.
{
"result": {
"upon_approval": "proceed",
"location": {
"link": "https://instance.service- now.com/api/now/table/cmn_location/108752c8c611227501d4ab0e392ba97f",
"value": "108752c8c611227501d4ab0e392ba97f"
},
"expected_start": "",
"reopen_count": "",
"sys_domain": {
"link": "https://instance.service- now.com/api/now/table/sys_user_group/global",
"value": "global"
},
"description": "",
"activity_due": "2016-01-22 16:12:37",
"sys_created_by": "glide.maint",
"resolved_at": "",
"assigned_to": {
"link": "https://instance.service- now.com/api/now/table/sys_user/681b365ec0a80164000fb0b05854a0cd",
"value": "681b365ec0a80164000fb0b05854a0cd"
},
"business_stc": "",
"wf_activity": "",
"sys_domain_path": "/",
"cmdb_ci": {
"link": "https://instance.service- now.com/api/now/table/cmdb_ci/281190e3c0a8000b003f593aa3f20ca6",
"value": "281190e3c0a8000b003f593aa3f20ca6"
},
"opened_by": {
"link": "https://instance.service- now.com/api/now/table/sys_user/glide.maint",
"value": "glide.maint"
},
"subcategory": "",
"comments": ""
}
}

Just create an object and use the objectmapper like:
Myclass myclass = objectMapper.readValue(json, Myclass.class);
But according to https://jsoneditoronline.org/ your json is not valid.
Used an online converter to create the classes, after removing the errors:
-----------------------------------com.example.AssignedTo.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class AssignedTo {
#SerializedName("link")
#Expose
private String link;
#SerializedName("value")
#Expose
private String value;
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
-----------------------------------com.example.CmdbCi.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class CmdbCi {
#SerializedName("link")
#Expose
private String link;
#SerializedName("value")
#Expose
private String value;
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
-----------------------------------com.example.Example.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("result")
#Expose
private Result result;
public Result getResult() {
return result;
}
public void setResult(Result result) {
this.result = result;
}
}
-----------------------------------com.example.Location.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Location {
#SerializedName("link")
#Expose
private String link;
#SerializedName("value")
#Expose
private String value;
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
-----------------------------------com.example.OpenedBy.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class OpenedBy {
#SerializedName("link")
#Expose
private String link;
#SerializedName("value")
#Expose
private String value;
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
-----------------------------------com.example.Result.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Result {
#SerializedName("upon_approval")
#Expose
private String uponApproval;
#SerializedName("location")
#Expose
private Location location;
#SerializedName("expected_start")
#Expose
private String expectedStart;
#SerializedName("reopen_count")
#Expose
private String reopenCount;
#SerializedName("sys_domain")
#Expose
private SysDomain sysDomain;
#SerializedName("description")
#Expose
private String description;
#SerializedName("activity_due")
#Expose
private String activityDue;
#SerializedName("sys_created_by")
#Expose
private String sysCreatedBy;
#SerializedName("resolved_at")
#Expose
private String resolvedAt;
#SerializedName("assigned_to")
#Expose
private AssignedTo assignedTo;
#SerializedName("business_stc")
#Expose
private String businessStc;
#SerializedName("wf_activity")
#Expose
private String wfActivity;
#SerializedName("sys_domain_path")
#Expose
private String sysDomainPath;
#SerializedName("cmdb_ci")
#Expose
private CmdbCi cmdbCi;
#SerializedName("opened_by")
#Expose
private OpenedBy openedBy;
#SerializedName("subcategory")
#Expose
private String subcategory;
#SerializedName("comments")
#Expose
private String comments;
public String getUponApproval() {
return uponApproval;
}
public void setUponApproval(String uponApproval) {
this.uponApproval = uponApproval;
}
public Location getLocation() {
return location;
}
public void setLocation(Location location) {
this.location = location;
}
public String getExpectedStart() {
return expectedStart;
}
public void setExpectedStart(String expectedStart) {
this.expectedStart = expectedStart;
}
public String getReopenCount() {
return reopenCount;
}
public void setReopenCount(String reopenCount) {
this.reopenCount = reopenCount;
}
public SysDomain getSysDomain() {
return sysDomain;
}
public void setSysDomain(SysDomain sysDomain) {
this.sysDomain = sysDomain;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getActivityDue() {
return activityDue;
}
public void setActivityDue(String activityDue) {
this.activityDue = activityDue;
}
public String getSysCreatedBy() {
return sysCreatedBy;
}
public void setSysCreatedBy(String sysCreatedBy) {
this.sysCreatedBy = sysCreatedBy;
}
public String getResolvedAt() {
return resolvedAt;
}
public void setResolvedAt(String resolvedAt) {
this.resolvedAt = resolvedAt;
}
public AssignedTo getAssignedTo() {
return assignedTo;
}
public void setAssignedTo(AssignedTo assignedTo) {
this.assignedTo = assignedTo;
}
public String getBusinessStc() {
return businessStc;
}
public void setBusinessStc(String businessStc) {
this.businessStc = businessStc;
}
public String getWfActivity() {
return wfActivity;
}
public void setWfActivity(String wfActivity) {
this.wfActivity = wfActivity;
}
public String getSysDomainPath() {
return sysDomainPath;
}
public void setSysDomainPath(String sysDomainPath) {
this.sysDomainPath = sysDomainPath;
}
public CmdbCi getCmdbCi() {
return cmdbCi;
}
public void setCmdbCi(CmdbCi cmdbCi) {
this.cmdbCi = cmdbCi;
}
public OpenedBy getOpenedBy() {
return openedBy;
}
public void setOpenedBy(OpenedBy openedBy) {
this.openedBy = openedBy;
}
public String getSubcategory() {
return subcategory;
}
public void setSubcategory(String subcategory) {
this.subcategory = subcategory;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
}
-----------------------------------com.example.SysDomain.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class SysDomain {
#SerializedName("link")
#Expose
private String link;
#SerializedName("value")
#Expose
private String value;
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
Edit: As i see, the code above will not work OOTB. I've got it working doeing the following steps:
Replace #SerializedName with #JsonProperty
then:
ObjectMapper mapper = new ObjectMapper();
Example example = mapper.readValue(json, Example.class);

Related

GSON throwing error when trying to pares a simple rest api response: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

I'm trying to parse a JSON like this
{
"meta": {
"limit": 20,
"next": null,
"offset": 0,
"previous": null,
"total_count": 1
},
"objects": [
{
"customer_id": "some-customer-id",
"id": 5,
"is_active": true,
"product_code": "some-product-code",
"resource_uri": "/api/v1/aws-marketplace/5/",
"support_subscription_id": "22"
}
]
}
generated for http://www.jsonschema2pojo.org I got his Java clases
package com.greenqloud.netappstats.collector.metrics.gqconsole.api;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class AwsMarketplace {
#SerializedName("meta")
#Expose
private Meta meta;
#SerializedName("objects")
#Expose
private List<Object> objects = null;
public Meta getMeta() {
return meta;
}
public void setMeta(Meta meta) {
this.meta = meta;
}
public List<Object> getObjects() {
return objects;
}
public void setObjects(List<Object> objects) {
this.objects = objects;
}
}
Meta class
package com.greenqloud.netappstats.collector.metrics.gqconsole.api;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Meta {
#SerializedName("limit")
#Expose
private int limit;
#SerializedName("next")
#Expose
private String next;
#SerializedName("offset")
#Expose
private int offset;
#SerializedName("previous")
#Expose
private String previous;
#SerializedName("total_count")
#Expose
private int totalCount;
public int getLimit() {
return limit;
}
public void setLimit(int limit) {
this.limit = limit;
}
public String getNext() {
return next;
}
public void setNext(String next) {
this.next = next;
}
public int getOffset() {
return offset;
}
public void setOffset(int offset) {
this.offset = offset;
}
public String getPrevious() {
return previous;
}
public void setPrevious(String previous) {
this.previous = previous;
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
}
Object class
package com.greenqloud.netappstats.collector.metrics.gqconsole.api;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Object {
#SerializedName("customer_id")
#Expose
private String customerId;
#SerializedName("id")
#Expose
private int id;
#SerializedName("is_active")
#Expose
private boolean isActive;
#SerializedName("product_code")
#Expose
private String productCode;
#SerializedName("resource_uri")
#Expose
private String resourceUri;
#SerializedName("support_subscription_id")
#Expose
private String supportSubscriptionId;
public String getCustomerId() {
return customerId;
}
public void setCustomerId(String customerId) {
this.customerId = customerId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public boolean isIsActive() {
return isActive;
}
public void setIsActive(boolean isActive) {
this.isActive = isActive;
}
public String getProductCode() {
return productCode;
}
public void setProductCode(String productCode) {
this.productCode = productCode;
}
public String getResourceUri() {
return resourceUri;
}
public void setResourceUri(String resourceUri) {
this.resourceUri = resourceUri;
}
public String getSupportSubscriptionId() {
return supportSubscriptionId;
}
public void setSupportSubscriptionId(String supportSubscriptionId) {
this.supportSubscriptionId = supportSubscriptionId;
}
}
But when trying to deserialise with this func
Type localVarReturnType = new TypeToken<List<InstanceCreatorForAwsMarketplace>>(){}.getType();
ApiResponse<List<InstanceCreatorForAwsMarketplace>> responseFromApiCleint = apiClient.execute(newCall, localVarReturnType);
I get the following error:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
Any idea what might be the issue? This looks like a fairly simple json that the rest service returns, but I have not been able to get it work, any help would be greatly appreciated.
Right after I had written the question, I found out the answer, of course the top level class should not be a list, just the class it self. But I have a secondary question, can the three mapper classes be mounted into one class, just a cosmetic issue?

How to Convert JSON to POJO class?

I checked the following json, it is valid, But http://www.jsonschema2pojo.org/ is not converting it into POJO object so I can fetch values from it, I need "nameValuePairs" object in following model. Please help. Thanks in advance
[
"order-chat-1",
{
"nameValuePairs":{
"chat":{
"nameValuePairs":{
"id":19,
"order_id":6,
"sender_id":10,
"receiver_id":3,
"message":"Hi",
"is_read":0,
"created_at":"2018-10-19 16:23:28",
"updated_at":"2018-10-19 16:23:28",
"is_sender":false
}
},
"message":"Hello from chef",
"message_type":"Message",
"is_sender":false
}
}
]
Here is the code to put on http://www.jsonschema2pojo.org/
{
"type":"object",
"properties":{
"chat":{
"type":"object",
"properties":{
"nameValuePairs":{
"type":"object",
"properties":{
"id": {"type": "integer"},
"order_id":{"type": "integer"},
"sender_id":{"type": "integer"},
"receiver_id":{"type": "integer"},
"message":{"type": "string"},
"is_read":{"type": "integer"},
"created_at":{"type": "string"},
"updated_at":{"type": "string"},
"is_sender":{"type": "boolean"}
}
}
}
},
"message":{"type": "string"},
"message_type":{"type": "string"},
"is_sender":{"type": "boolean"}
}
}
That produces the following POJO's where Example.class is your root object, change the name as you want.
-----------------------------------com.example.Chat.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Chat {
#SerializedName("nameValuePairs")
#Expose
private NameValuePairs nameValuePairs;
public NameValuePairs getNameValuePairs() {
return nameValuePairs;
}
public void setNameValuePairs(NameValuePairs nameValuePairs) {
this.nameValuePairs = nameValuePairs;
}
public Chat withNameValuePairs(NameValuePairs nameValuePairs) {
this.nameValuePairs = nameValuePairs;
return this;
}
}
-----------------------------------com.example.Example.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("chat")
#Expose
private Chat chat;
#SerializedName("message")
#Expose
private String message;
#SerializedName("message_type")
#Expose
private String messageType;
#SerializedName("is_sender")
#Expose
private boolean isSender;
public Chat getChat() {
return chat;
}
public void setChat(Chat chat) {
this.chat = chat;
}
public Example withChat(Chat chat) {
this.chat = chat;
return this;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Example withMessage(String message) {
this.message = message;
return this;
}
public String getMessageType() {
return messageType;
}
public void setMessageType(String messageType) {
this.messageType = messageType;
}
public Example withMessageType(String messageType) {
this.messageType = messageType;
return this;
}
public boolean isIsSender() {
return isSender;
}
public void setIsSender(boolean isSender) {
this.isSender = isSender;
}
public Example withIsSender(boolean isSender) {
this.isSender = isSender;
return this;
}
}
-----------------------------------com.example.NameValuePairs.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class NameValuePairs {
#SerializedName("id")
#Expose
private int id;
#SerializedName("order_id")
#Expose
private int orderId;
#SerializedName("sender_id")
#Expose
private int senderId;
#SerializedName("receiver_id")
#Expose
private int receiverId;
#SerializedName("message")
#Expose
private String message;
#SerializedName("is_read")
#Expose
private int isRead;
#SerializedName("created_at")
#Expose
private String createdAt;
#SerializedName("updated_at")
#Expose
private String updatedAt;
#SerializedName("is_sender")
#Expose
private boolean isSender;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public NameValuePairs withId(int id) {
this.id = id;
return this;
}
public int getOrderId() {
return orderId;
}
public void setOrderId(int orderId) {
this.orderId = orderId;
}
public NameValuePairs withOrderId(int orderId) {
this.orderId = orderId;
return this;
}
public int getSenderId() {
return senderId;
}
public void setSenderId(int senderId) {
this.senderId = senderId;
}
public NameValuePairs withSenderId(int senderId) {
this.senderId = senderId;
return this;
}
public int getReceiverId() {
return receiverId;
}
public void setReceiverId(int receiverId) {
this.receiverId = receiverId;
}
public NameValuePairs withReceiverId(int receiverId) {
this.receiverId = receiverId;
return this;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public NameValuePairs withMessage(String message) {
this.message = message;
return this;
}
public int getIsRead() {
return isRead;
}
public void setIsRead(int isRead) {
this.isRead = isRead;
}
public NameValuePairs withIsRead(int isRead) {
this.isRead = isRead;
return this;
}
public String getCreatedAt() {
return createdAt;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
public NameValuePairs withCreatedAt(String createdAt) {
this.createdAt = createdAt;
return this;
}
public String getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(String updatedAt) {
this.updatedAt = updatedAt;
}
public NameValuePairs withUpdatedAt(String updatedAt) {
this.updatedAt = updatedAt;
return this;
}
public boolean isIsSender() {
return isSender;
}
public void setIsSender(boolean isSender) {
this.isSender = isSender;
}
public NameValuePairs withIsSender(boolean isSender) {
this.isSender = isSender;
return this;
}
}
It is valid from JavaScript prospective, but not form standard Java libraries such as GSON, Jackson or whatever www.jsonschema2pojo.org uses.
There are two things:
It is an Array on top
There are two different types in that array String and an Object
It can be converted only to Object[] or Collection<Object> (e.g.List, Set etc).
But to do that you have to have a custom Serializer/Deserializer.
I worked with another technique to resolve this, I converted this Object to String through Gson() and after that with subString method I removed the first 16 characters and the last character of the newly created string, then I Converted that String to POJO Object.

Using GSON to parse an JSON object with an array of elements

How can I use GSON to parse the following JSON object:
{
"ProductsByCategory": [
{.....},
{.....},
{.....},
{.....},
]
}
The JSON object contains an array of elements. I am using GSON to try and parse the JSON and have the following POJO classes to assist me with this.
public class ProductItems {
#SerializedName("ProductsByCategory")
#Expose
private List<ProductsByCategory> productsByCategory = null;
public List<ProductsByCategory> getProductsByCategory() {
return productsByCategory;
}
public void setProductsByCategory(List<ProductsByCategory> productsByCategory) {
this.productsByCategory = productsByCategory;
}
}
public class ProductsByCategory {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("slug")
#Expose
private String slug;
#SerializedName("permalink")
#Expose
private String permalink;
#SerializedName("date_created")
#Expose
private String dateCreated;
#SerializedName("date_created_gmt")
#Expose
private String dateCreatedGmt;
#SerializedName("date_modified")
#Expose
private String dateModified;
#SerializedName("date_modified_gmt")
#Expose
private String dateModifiedGmt;
#SerializedName("type")
#Expose
private String type;
#SerializedName("status")
#Expose
private String status;
#SerializedName("featured")
#Expose
private Boolean featured;
#SerializedName("catalog_visibility")
#Expose
private String catalogVisibility;
#SerializedName("description")
#Expose
private String description;
#SerializedName("short_description")
#Expose
private String shortDescription;
#SerializedName("sku")
#Expose
private String sku;
#SerializedName("price")
#Expose
private String price;
#SerializedName("regular_price")
#Expose
private String regularPrice;
#SerializedName("sale_price")
#Expose
private String salePrice;
#SerializedName("date_on_sale_from")
#Expose
private Object dateOnSaleFrom;
#SerializedName("date_on_sale_from_gmt")
#Expose
private Object dateOnSaleFromGmt;
#SerializedName("date_on_sale_to")
#Expose
private Object dateOnSaleTo;
#SerializedName("date_on_sale_to_gmt")
#Expose
private Object dateOnSaleToGmt;
#SerializedName("price_html")
#Expose
private String priceHtml;
#SerializedName("on_sale")
#Expose
private Boolean onSale;
#SerializedName("purchasable")
#Expose
private Boolean purchasable;
#SerializedName("total_sales")
#Expose
private Integer totalSales;
#SerializedName("virtual")
#Expose
private Boolean virtual;
#SerializedName("downloadable")
#Expose
private Boolean downloadable;
#SerializedName("downloads")
#Expose
private List<Object> downloads = null;
#SerializedName("download_limit")
#Expose
private Integer downloadLimit;
#SerializedName("download_expiry")
#Expose
private Integer downloadExpiry;
#SerializedName("external_url")
#Expose
private String externalUrl;
#SerializedName("button_text")
#Expose
private String buttonText;
#SerializedName("tax_status")
#Expose
private String taxStatus;
#SerializedName("tax_class")
#Expose
private String taxClass;
#SerializedName("manage_stock")
#Expose
private Boolean manageStock;
#SerializedName("stock_quantity")
#Expose
private Integer stockQuantity;
#SerializedName("in_stock")
#Expose
private Boolean inStock;
#SerializedName("backorders")
#Expose
private String backorders;
#SerializedName("backorders_allowed")
#Expose
private Boolean backordersAllowed;
#SerializedName("backordered")
#Expose
private Boolean backordered;
#SerializedName("sold_individually")
#Expose
private Boolean soldIndividually;
#SerializedName("weight")
#Expose
private String weight;
#SerializedName("dimensions")
#Expose
private Dimensions dimensions;
#SerializedName("shipping_required")
#Expose
private Boolean shippingRequired;
#SerializedName("shipping_taxable")
#Expose
private Boolean shippingTaxable;
#SerializedName("shipping_class")
#Expose
private String shippingClass;
#SerializedName("shipping_class_id")
#Expose
private Integer shippingClassId;
#SerializedName("reviews_allowed")
#Expose
private Boolean reviewsAllowed;
#SerializedName("average_rating")
#Expose
private String averageRating;
#SerializedName("rating_count")
#Expose
private Integer ratingCount;
#SerializedName("related_ids")
#Expose
private List<Integer> relatedIds = null;
#SerializedName("upsell_ids")
#Expose
private List<Object> upsellIds = null;
#SerializedName("cross_sell_ids")
#Expose
private List<Object> crossSellIds = null;
#SerializedName("parent_id")
#Expose
private Integer parentId;
#SerializedName("purchase_note")
#Expose
private String purchaseNote;
#SerializedName("categories")
#Expose
private List<Category> categories = null;
#SerializedName("tags")
#Expose
private List<Object> tags = null;
#SerializedName("images")
#Expose
private List<Image> images = null;
#SerializedName("attributes")
#Expose
private List<Attribute> attributes = null;
#SerializedName("default_attributes")
#Expose
private List<Object> defaultAttributes = null;
#SerializedName("variations")
#Expose
private List<Integer> variations = null;
#SerializedName("grouped_products")
#Expose
private List<Object> groupedProducts = null;
#SerializedName("menu_order")
#Expose
private Integer menuOrder;
#SerializedName("meta_data")
#Expose
private List<MetaDatum> metaData = null;
#SerializedName("_links")
#Expose
private Links links;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSlug() {
return slug;
}
public void setSlug(String slug) {
this.slug = slug;
}
public String getPermalink() {
return permalink;
}
public void setPermalink(String permalink) {
this.permalink = permalink;
}
public String getDateCreated() {
return dateCreated;
}
public void setDateCreated(String dateCreated) {
this.dateCreated = dateCreated;
}
public String getDateCreatedGmt() {
return dateCreatedGmt;
}
public void setDateCreatedGmt(String dateCreatedGmt) {
this.dateCreatedGmt = dateCreatedGmt;
}
public String getDateModified() {
return dateModified;
}
public void setDateModified(String dateModified) {
this.dateModified = dateModified;
}
public String getDateModifiedGmt() {
return dateModifiedGmt;
}
public void setDateModifiedGmt(String dateModifiedGmt) {
this.dateModifiedGmt = dateModifiedGmt;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Boolean getFeatured() {
return featured;
}
public void setFeatured(Boolean featured) {
this.featured = featured;
}
public String getCatalogVisibility() {
return catalogVisibility;
}
public void setCatalogVisibility(String catalogVisibility) {
this.catalogVisibility = catalogVisibility;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getShortDescription() {
return shortDescription;
}
public void setShortDescription(String shortDescription) {
this.shortDescription = shortDescription;
}
public String getSku() {
return sku;
}
public void setSku(String sku) {
this.sku = sku;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getRegularPrice() {
return regularPrice;
}
public void setRegularPrice(String regularPrice) {
this.regularPrice = regularPrice;
}
public String getSalePrice() {
return salePrice;
}
public void setSalePrice(String salePrice) {
this.salePrice = salePrice;
}
public Object getDateOnSaleFrom() {
return dateOnSaleFrom;
}
public void setDateOnSaleFrom(Object dateOnSaleFrom) {
this.dateOnSaleFrom = dateOnSaleFrom;
}
public Object getDateOnSaleFromGmt() {
return dateOnSaleFromGmt;
}
public void setDateOnSaleFromGmt(Object dateOnSaleFromGmt) {
this.dateOnSaleFromGmt = dateOnSaleFromGmt;
}
public Object getDateOnSaleTo() {
return dateOnSaleTo;
}
public void setDateOnSaleTo(Object dateOnSaleTo) {
this.dateOnSaleTo = dateOnSaleTo;
}
public Object getDateOnSaleToGmt() {
return dateOnSaleToGmt;
}
public void setDateOnSaleToGmt(Object dateOnSaleToGmt) {
this.dateOnSaleToGmt = dateOnSaleToGmt;
}
public String getPriceHtml() {
return priceHtml;
}
public void setPriceHtml(String priceHtml) {
this.priceHtml = priceHtml;
}
public Boolean getOnSale() {
return onSale;
}
public void setOnSale(Boolean onSale) {
this.onSale = onSale;
}
public Boolean getPurchasable() {
return purchasable;
}
public void setPurchasable(Boolean purchasable) {
this.purchasable = purchasable;
}
public Integer getTotalSales() {
return totalSales;
}
public void setTotalSales(Integer totalSales) {
this.totalSales = totalSales;
}
public Boolean getVirtual() {
return virtual;
}
public void setVirtual(Boolean virtual) {
this.virtual = virtual;
}
public Boolean getDownloadable() {
return downloadable;
}
public void setDownloadable(Boolean downloadable) {
this.downloadable = downloadable;
}
public List<Object> getDownloads() {
return downloads;
}
public void setDownloads(List<Object> downloads) {
this.downloads = downloads;
}
public Integer getDownloadLimit() {
return downloadLimit;
}
public void setDownloadLimit(Integer downloadLimit) {
this.downloadLimit = downloadLimit;
}
public Integer getDownloadExpiry() {
return downloadExpiry;
}
public void setDownloadExpiry(Integer downloadExpiry) {
this.downloadExpiry = downloadExpiry;
}
public String getExternalUrl() {
return externalUrl;
}
public void setExternalUrl(String externalUrl) {
this.externalUrl = externalUrl;
}
public String getButtonText() {
return buttonText;
}
public void setButtonText(String buttonText) {
this.buttonText = buttonText;
}
public String getTaxStatus() {
return taxStatus;
}
public void setTaxStatus(String taxStatus) {
this.taxStatus = taxStatus;
}
public String getTaxClass() {
return taxClass;
}
public void setTaxClass(String taxClass) {
this.taxClass = taxClass;
}
public Boolean getManageStock() {
return manageStock;
}
public void setManageStock(Boolean manageStock) {
this.manageStock = manageStock;
}
public Integer getStockQuantity() {
return stockQuantity;
}
public void setStockQuantity(Integer stockQuantity) {
this.stockQuantity = stockQuantity;
}
public Boolean getInStock() {
return inStock;
}
public void setInStock(Boolean inStock) {
this.inStock = inStock;
}
public String getBackorders() {
return backorders;
}
public void setBackorders(String backorders) {
this.backorders = backorders;
}
public Boolean getBackordersAllowed() {
return backordersAllowed;
}
public void setBackordersAllowed(Boolean backordersAllowed) {
this.backordersAllowed = backordersAllowed;
}
public Boolean getBackordered() {
return backordered;
}
public void setBackordered(Boolean backordered) {
this.backordered = backordered;
}
public Boolean getSoldIndividually() {
return soldIndividually;
}
public void setSoldIndividually(Boolean soldIndividually) {
this.soldIndividually = soldIndividually;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public Dimensions getDimensions() {
return dimensions;
}
public void setDimensions(Dimensions dimensions) {
this.dimensions = dimensions;
}
public Boolean getShippingRequired() {
return shippingRequired;
}
public void setShippingRequired(Boolean shippingRequired) {
this.shippingRequired = shippingRequired;
}
public Boolean getShippingTaxable() {
return shippingTaxable;
}
public void setShippingTaxable(Boolean shippingTaxable) {
this.shippingTaxable = shippingTaxable;
}
public String getShippingClass() {
return shippingClass;
}
public void setShippingClass(String shippingClass) {
this.shippingClass = shippingClass;
}
public Integer getShippingClassId() {
return shippingClassId;
}
public void setShippingClassId(Integer shippingClassId) {
this.shippingClassId = shippingClassId;
}
public Boolean getReviewsAllowed() {
return reviewsAllowed;
}
public void setReviewsAllowed(Boolean reviewsAllowed) {
this.reviewsAllowed = reviewsAllowed;
}
public String getAverageRating() {
return averageRating;
}
public void setAverageRating(String averageRating) {
this.averageRating = averageRating;
}
public Integer getRatingCount() {
return ratingCount;
}
public void setRatingCount(Integer ratingCount) {
this.ratingCount = ratingCount;
}
public List<Integer> getRelatedIds() {
return relatedIds;
}
public void setRelatedIds(List<Integer> relatedIds) {
this.relatedIds = relatedIds;
}
public List<Object> getUpsellIds() {
return upsellIds;
}
public void setUpsellIds(List<Object> upsellIds) {
this.upsellIds = upsellIds;
}
public List<Object> getCrossSellIds() {
return crossSellIds;
}
public void setCrossSellIds(List<Object> crossSellIds) {
this.crossSellIds = crossSellIds;
}
public Integer getParentId() {
return parentId;
}
public void setParentId(Integer parentId) {
this.parentId = parentId;
}
public String getPurchaseNote() {
return purchaseNote;
}
public void setPurchaseNote(String purchaseNote) {
this.purchaseNote = purchaseNote;
}
public List<Category> getCategories() {
return categories;
}
public void setCategories(List<Category> categories) {
this.categories = categories;
}
public List<Object> getTags() {
return tags;
}
public void setTags(List<Object> tags) {
this.tags = tags;
}
public List<Image> getImages() {
return images;
}
public void setImages(List<Image> images) {
this.images = images;
}
public List<Attribute> getAttributes() {
return attributes;
}
public void setAttributes(List<Attribute> attributes) {
this.attributes = attributes;
}
public List<Object> getDefaultAttributes() {
return defaultAttributes;
}
public void setDefaultAttributes(List<Object> defaultAttributes) {
this.defaultAttributes = defaultAttributes;
}
public List<Integer> getVariations() {
return variations;
}
public void setVariations(List<Integer> variations) {
this.variations = variations;
}
public List<Object> getGroupedProducts() {
return groupedProducts;
}
public void setGroupedProducts(List<Object> groupedProducts) {
this.groupedProducts = groupedProducts;
}
public Integer getMenuOrder() {
return menuOrder;
}
public void setMenuOrder(Integer menuOrder) {
this.menuOrder = menuOrder;
}
public List<MetaDatum> getMetaData() {
return metaData;
}
public void setMetaData(List<MetaDatum> metaData) {
this.metaData = metaData;
}
public Links getLinks() {
return links;
}
public void setLinks(Links links) {
this.links = links;
}
}
The code that I use is the following:
public void onResponse(Call call, Response response) throws IOException
{
String mMessage = response.body().string();
if (response.isSuccessful())
{
try
{
Gson gson = new Gson();
final ProductItems categoryProducts = gson.fromJson(mMessage, ProductItems.class);
response.close();
}
catch (Exception e)
{
Log.e("Error", "Failed to upload");
e.printStackTrace();
}
However, I get the following error: GSON throwing “Expected BEGIN_OBJECT but was BEGIN_ARRAY.
I have tried to change the ProductItems class to taking an object for productbycategories but then I get the following error: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 2324 path $.ProductsByCategory[0].meta_data[0].value. I am now a bit confused.
The reason you get this error is that the data is not consistent with the way the POJO is generated.
This is the specific part of the data that has the issue:
"meta_data": [
{
"id": 14232,
"key": "_vc_post_settings",
"value": {
"vc_grid_id": []
}
},
{
"id": 14273,
"key": "fb_product_description",
"value": ""
},
{
"id": 14274,
"key": "fb_visibility",
"value": "1"
},
Notice how the "meta_data" field is an array of objects and that these objects contain a "value" field. The data type of the "value" varies- sometimes it's an object and other times it's a string.
One possible solution would be to change the MetaDatum class so that the value is an Object:
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class MetaDatum {
...
#SerializedName("value")
#Expose
private Object value;
...
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
}

How can I set My Json Value in Adapter

I Am Having two JsonArray in Which there is JsonObject I have Got the String of each value but the problem is that when i am passing i into adapter I am getting indexOutofbound exeption because my value are getting Store in my object class so can any one help me how can i send my data to Object so that i can inflate to recyclerView.
private void callola() {
progressDialog = new ProgressDialog(CabBookingActivity.this);
progressDialog.setMessage("Loading ...");
progressDialog.setCancelable(false);
progressDialog.show();
final RequestQueue queue = Volley.newRequestQueue(CabBookingActivity.this);
String url = "https://www.reboundindia.com/app/application/ola/ride_estimate.php";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.setCancelable(true);
progressDialog.dismiss();
Log.e("sushil Call ola response", response);
try {
JSONObject mainObj = new JSONObject(response);
arrayList = new ArrayList<>();
String result = mainObj.getString("result");
int i, j;
ArrayList categoriess, Ride;
if (result.equals("606")) {
JSONObject message = mainObj.getJSONObject("message");
categories = message.getJSONArray("categories");
ride_estimate = message.getJSONArray("ride_estimate");
// JSONArray ride_estimate = message.getJSONArray("ride_estimate");
for (i = 0; i < categories.length(); i++) {
Log.e("sushil", String.valueOf(i));
jsonObject = categories.getJSONObject(i);
id = jsonObject.getString("id");
display_name = jsonObject.getString("display_name");
image = jsonObject.getString("image");
eta = jsonObject.getString("eta");
Log.e("OutPut", id + " " + eta + " " + image + " " + amount_min + " " + amount_max);
}
for (j = 0; j < ride_estimate.length(); j++) {
Log.e("sushil", String.valueOf(j));
rideestimate = ride_estimate.getJSONObject(j);
distance = rideestimate.getString("distance");
amount_min = rideestimate.getString("amount_min");
amount_max = rideestimate.getString("amount_max");
category = rideestimate.getString("category");
}
}
OlaUberModel olaUberModel = new OlaUberModel(category, display_name, amount_min, eta, image, amount_max);
arrayList.add(olaUberModel);
Log.e("sushil ride_estimate", distance + " " + amount_min + " " + amount_max);
AdapterOlaUber adapterOlaUber = new AdapterOlaUber(context, arrayList, CabBookingActivity.this);
recyclerView.setAdapter(adapterOlaUber);
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Log.e("error", error.toString());
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("pickup_lat", "" + pickLat);
params.put("pickup_lng", "" + pickLong);
params.put("drop_lat", String.valueOf(dropLat));
params.put("drop_lng", String.valueOf(dropLong));
params.put("category", "all");
params.put("token", token);
Log.e("sushil param", String.valueOf(params));
return params;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
90000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(stringRequest);
}
Here is my JSONRESPONSE
{
"result":"606",
"message":{
"categories":[
{
"id":"micro",
"display_name":"Micro",
"currency":"INR",
"distance_unit":"kilometre",
"time_unit":"minute",
"eta":5,
"distance":"0.7",
"ride_later_enabled":"true",
"image":"http:\/\/d1foexe15giopy.cloudfront.net\/micro.png",
"cancellation_policy":{
"cancellation_charge":50,
"currency":"INR",
"cancellation_charge_applies_after_time":5,
"time_unit":"minute"
},
"fare_breakup":[
{
"type":"flat_rate",
"minimum_distance":0,
"minimum_time":0,
"base_fare":50,
"minimum_fare":60,
"cost_per_distance":6,
"waiting_cost_per_minute":0,
"ride_cost_per_minute":1.5,
"surcharge":[
],
"rates_lower_than_usual":false,
"rates_higher_than_usual":false
}
]
},
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ }
],
"ride_estimate":[
{
"category":"prime_play",
"distance":3.99,
"travel_time_in_minutes":30,
"amount_min":155,
"amount_max":163,
"discounts":{
"discount_type":null,
"discount_code":null,
"discount_mode":null,
"discount":0,
"cashback":0
}
},
{ },
{ },
{ },
{ },
{ },
{ },
{ }
]
}
}
My Problem is that how can send the data in model.
My Model Should contain data Like id,displayName,amountMin,eta,image,amountMax
First of all you need to make two different models for category and ride_estimate.Because they both are in different loops. Also try this
for (j = 0; j < ride_estimate.length(); j++) {
Log.e("sushil", String.valueOf(j));
rideestimate = ride_estimate.getJSONObject(j);
distance = rideestimate.getString("distance");
amount_min = rideestimate.getString("amount_min");
amount_max = rideestimate.getString("amount_max");
category = rideestimate.getString("category");
OlaUberModel olaUberModel = new OlaUberModel(category, display_name, amount_min, eta, image, amount_max);
arrayList.add(olaUberModel);
}
May be this would helpful for you..
Thanks!
replace
eta = jsonObject.getString("eta");
by
int eta = jsonObject.getInt("eta");
On the basis of id of any cab type "prime" you can fetch image. what say
create some class as per your data
-----------------------------------com.example.CancellationPolicy.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class CancellationPolicy {
#SerializedName("cancellation_charge")
#Expose
private Integer cancellationCharge;
#SerializedName("currency")
#Expose
private String currency;
#SerializedName("cancellation_charge_applies_after_time")
#Expose
private Integer cancellationChargeAppliesAfterTime;
#SerializedName("time_unit")
#Expose
private String timeUnit;
public Integer getCancellationCharge() {
return cancellationCharge;
}
public void setCancellationCharge(Integer cancellationCharge) {
this.cancellationCharge = cancellationCharge;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public Integer getCancellationChargeAppliesAfterTime() {
return cancellationChargeAppliesAfterTime;
}
public void setCancellationChargeAppliesAfterTime(Integer cancellationChargeAppliesAfterTime) {
this.cancellationChargeAppliesAfterTime = cancellationChargeAppliesAfterTime;
}
public String getTimeUnit() {
return timeUnit;
}
public void setTimeUnit(String timeUnit) {
this.timeUnit = timeUnit;
}
}
-----------------------------------com.example.Category.java-----------------------------------
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Category {
#SerializedName("id")
#Expose
private String id;
#SerializedName("display_name")
#Expose
private String displayName;
#SerializedName("currency")
#Expose
private String currency;
#SerializedName("distance_unit")
#Expose
private String distanceUnit;
#SerializedName("time_unit")
#Expose
private String timeUnit;
#SerializedName("eta")
#Expose
private Integer eta;
#SerializedName("distance")
#Expose
private String distance;
#SerializedName("ride_later_enabled")
#Expose
private String rideLaterEnabled;
#SerializedName("image")
#Expose
private String image;
#SerializedName("cancellation_policy")
#Expose
private CancellationPolicy cancellationPolicy;
#SerializedName("fare_breakup")
#Expose
private List<FareBreakup> fareBreakup = null;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public String getDistanceUnit() {
return distanceUnit;
}
public void setDistanceUnit(String distanceUnit) {
this.distanceUnit = distanceUnit;
}
public String getTimeUnit() {
return timeUnit;
}
public void setTimeUnit(String timeUnit) {
this.timeUnit = timeUnit;
}
public Integer getEta() {
return eta;
}
public void setEta(Integer eta) {
this.eta = eta;
}
public String getDistance() {
return distance;
}
public void setDistance(String distance) {
this.distance = distance;
}
public String getRideLaterEnabled() {
return rideLaterEnabled;
}
public void setRideLaterEnabled(String rideLaterEnabled) {
this.rideLaterEnabled = rideLaterEnabled;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public CancellationPolicy getCancellationPolicy() {
return cancellationPolicy;
}
public void setCancellationPolicy(CancellationPolicy cancellationPolicy) {
this.cancellationPolicy = cancellationPolicy;
}
public List<FareBreakup> getFareBreakup() {
return fareBreakup;
}
public void setFareBreakup(List<FareBreakup> fareBreakup) {
this.fareBreakup = fareBreakup;
}
}
-----------------------------------com.example.Discounts.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Discounts {
#SerializedName("discount_type")
#Expose
private Object discountType;
#SerializedName("discount_code")
#Expose
private Object discountCode;
#SerializedName("discount_mode")
#Expose
private Object discountMode;
#SerializedName("discount")
#Expose
private Integer discount;
#SerializedName("cashback")
#Expose
private Integer cashback;
public Object getDiscountType() {
return discountType;
}
public void setDiscountType(Object discountType) {
this.discountType = discountType;
}
public Object getDiscountCode() {
return discountCode;
}
public void setDiscountCode(Object discountCode) {
this.discountCode = discountCode;
}
public Object getDiscountMode() {
return discountMode;
}
public void setDiscountMode(Object discountMode) {
this.discountMode = discountMode;
}
public Integer getDiscount() {
return discount;
}
public void setDiscount(Integer discount) {
this.discount = discount;
}
public Integer getCashback() {
return cashback;
}
public void setCashback(Integer cashback) {
this.cashback = cashback;
}
}
-----------------------------------com.example.Example.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("result")
#Expose
private String result;
#SerializedName("message")
#Expose
private Message message;
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public Message getMessage() {
return message;
}
public void setMessage(Message message) {
this.message = message;
}
}
-----------------------------------com.example.FareBreakup.java-----------------------------------
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class FareBreakup {
#SerializedName("type")
#Expose
private String type;
#SerializedName("minimum_distance")
#Expose
private Integer minimumDistance;
#SerializedName("minimum_time")
#Expose
private Integer minimumTime;
#SerializedName("base_fare")
#Expose
private Integer baseFare;
#SerializedName("minimum_fare")
#Expose
private Integer minimumFare;
#SerializedName("cost_per_distance")
#Expose
private Integer costPerDistance;
#SerializedName("waiting_cost_per_minute")
#Expose
private Integer waitingCostPerMinute;
#SerializedName("ride_cost_per_minute")
#Expose
private Double rideCostPerMinute;
#SerializedName("surcharge")
#Expose
private List<Object> surcharge = null;
#SerializedName("rates_lower_than_usual")
#Expose
private Boolean ratesLowerThanUsual;
#SerializedName("rates_higher_than_usual")
#Expose
private Boolean ratesHigherThanUsual;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Integer getMinimumDistance() {
return minimumDistance;
}
public void setMinimumDistance(Integer minimumDistance) {
this.minimumDistance = minimumDistance;
}
public Integer getMinimumTime() {
return minimumTime;
}
public void setMinimumTime(Integer minimumTime) {
this.minimumTime = minimumTime;
}
public Integer getBaseFare() {
return baseFare;
}
public void setBaseFare(Integer baseFare) {
this.baseFare = baseFare;
}
public Integer getMinimumFare() {
return minimumFare;
}
public void setMinimumFare(Integer minimumFare) {
this.minimumFare = minimumFare;
}
public Integer getCostPerDistance() {
return costPerDistance;
}
public void setCostPerDistance(Integer costPerDistance) {
this.costPerDistance = costPerDistance;
}
public Integer getWaitingCostPerMinute() {
return waitingCostPerMinute;
}
public void setWaitingCostPerMinute(Integer waitingCostPerMinute) {
this.waitingCostPerMinute = waitingCostPerMinute;
}
public Double getRideCostPerMinute() {
return rideCostPerMinute;
}
public void setRideCostPerMinute(Double rideCostPerMinute) {
this.rideCostPerMinute = rideCostPerMinute;
}
public List<Object> getSurcharge() {
return surcharge;
}
public void setSurcharge(List<Object> surcharge) {
this.surcharge = surcharge;
}
public Boolean getRatesLowerThanUsual() {
return ratesLowerThanUsual;
}
public void setRatesLowerThanUsual(Boolean ratesLowerThanUsual) {
this.ratesLowerThanUsual = ratesLowerThanUsual;
}
public Boolean getRatesHigherThanUsual() {
return ratesHigherThanUsual;
}
public void setRatesHigherThanUsual(Boolean ratesHigherThanUsual) {
this.ratesHigherThanUsual = ratesHigherThanUsual;
}
}
-----------------------------------com.example.Message.java-----------------------------------
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Message {
#SerializedName("categories")
#Expose
private List<Category> categories = null;
#SerializedName("ride_estimate")
#Expose
private List<RideEstimate> rideEstimate = null;
public List<Category> getCategories() {
return categories;
}
public void setCategories(List<Category> categories) {
this.categories = categories;
}
public List<RideEstimate> getRideEstimate() {
return rideEstimate;
}
public void setRideEstimate(List<RideEstimate> rideEstimate) {
this.rideEstimate = rideEstimate;
}
}
-----------------------------------com.example.RideEstimate.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class RideEstimate {
#SerializedName("category")
#Expose
private String category;
#SerializedName("distance")
#Expose
private Double distance;
#SerializedName("travel_time_in_minutes")
#Expose
private Integer travelTimeInMinutes;
#SerializedName("amount_min")
#Expose
private Integer amountMin;
#SerializedName("amount_max")
#Expose
private Integer amountMax;
#SerializedName("discounts")
#Expose
private Discounts discounts;
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public Double getDistance() {
return distance;
}
public void setDistance(Double distance) {
this.distance = distance;
}
public Integer getTravelTimeInMinutes() {
return travelTimeInMinutes;
}
public void setTravelTimeInMinutes(Integer travelTimeInMinutes) {
this.travelTimeInMinutes = travelTimeInMinutes;
}
public Integer getAmountMin() {
return amountMin;
}
public void setAmountMin(Integer amountMin) {
this.amountMin = amountMin;
}
public Integer getAmountMax() {
return amountMax;
}
public void setAmountMax(Integer amountMax) {
this.amountMax = amountMax;
}
public Discounts getDiscounts() {
return discounts;
}
public void setDiscounts(Discounts discounts) {
this.discounts = discounts;
}
}
Now compile a library compile 'com.google.code.gson:gson:2.8.2'
then write few line to get your data fill in class
Gson gson = new Gson();
Example example = gson.fromJson(mainObj, Example.class);
Now you can try to fetch your categories like this
example.getCategories();

How to parse all json objects and send them inside a class?

This is the response JSON from Volley:
{
"status":true,
"data":{
"product_id":"12",
"product_ogpm_id":"OGPR1000485",
"product_part_number":"6ED1 057-1AA01-0BA0",
"escape_part_number":"6ed10571aa010ba0",
"product_name":"USB PC Cable",
"product_uom":"",
"product_image":"",
"product_description":"",
"product_manufacturer":"Siemens",
"manufacturer_id":"4",
"replace_id":"0",
"replace_date":"0000-00-00 00:00:00",
"product_added_date":"2017-09-12 00:57:15",
"product_added_by":"Jayank Chopra",
"product_modified_date":"0000-00-00 00:00:00",
"product_modified_by":"",
"product_status":"1",
"manufacturer_name":"Siemens",
"contracted_id":"1",
"data_sheets":[
]
},
"message":"Product found!"
}
For Parsing I use Gson Like this:
/* BarcodeSearchResponse responseObj = new Gson().fromJson(responseJson.toString(), BarcodeSearchResponse.class);
where BarcodeSearchResponse class is this:
public class BarcodeSearchResponse{
public ArrayList<ScanData> data;
}
*/
And ScanData is a class that contains :
public class ScanData implements Parcelable{
#SerializedName("product_id")
#Expose
private String productId;
#SerializedName("product_ogpm_id")
#Expose
private String productOgpmId;
#SerializedName("product_part_number")
#Expose
private String productPartNumber;
#SerializedName("escape_part_number")
#Expose
private String escapePartNumber;
#SerializedName("product_name")
#Expose
private String productName;
#SerializedName("product_uom")
#Expose
private String productUom;
#SerializedName("product_image")
#Expose
private String productImage;
#SerializedName("product_description")
#Expose
private String productDescription;
#SerializedName("product_manufacturer")
#Expose
private String productManufacturer;
#SerializedName("manufacturer_id")
#Expose
private String manufacturerId;
#SerializedName("replace_id")
#Expose
private String replaceId;
#SerializedName("replace_date")
#Expose
private String replaceDate;
#SerializedName("product_added_date")
#Expose
private String productAddedDate;
#SerializedName("product_added_by")
#Expose
private String productAddedBy;
#SerializedName("product_modified_date")
#Expose
private String productModifiedDate;
#SerializedName("product_modified_by")
#Expose
private String productModifiedBy;
#SerializedName("product_status")
#Expose
private String productStatus;
#SerializedName("manufacturer_name")
#Expose
private String manufacturerName;
#SerializedName("contracted_id")
#Expose
private String contractedId;
#SerializedName("data_sheets")
#Expose
private List<Object> dataSheets = null;
protected ScanData(Parcel in) {
productId = in.readString();
productOgpmId = in.readString();
productPartNumber = in.readString();
escapePartNumber = in.readString();
productName = in.readString();
productUom = in.readString();
productImage = in.readString();
productDescription = in.readString();
productManufacturer = in.readString();
manufacturerId = in.readString();
replaceId = in.readString();
replaceDate = in.readString();
productAddedDate = in.readString();
productAddedBy = in.readString();
productModifiedDate = in.readString();
productModifiedBy = in.readString();
productStatus = in.readString();
manufacturerName = in.readString();
contractedId = in.readString();
}
public static final Creator<ScanData> CREATOR = new Creator<ScanData>() {
#Override
public ScanData createFromParcel(Parcel in) {
return new ScanData(in);
}
#Override
public ScanData[] newArray(int size) {
return new ScanData[size];
}
};
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public String getProductOgpmId() {
return productOgpmId;
}
public void setProductOgpmId(String productOgpmId) {
this.productOgpmId = productOgpmId;
}
public String getProductPartNumber() {
return productPartNumber;
}
public void setProductPartNumber(String productPartNumber) {
this.productPartNumber = productPartNumber;
}
public String getEscapePartNumber() {
return escapePartNumber;
}
public void setEscapePartNumber(String escapePartNumber) {
this.escapePartNumber = escapePartNumber;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getProductUom() {
return productUom;
}
public void setProductUom(String productUom) {
this.productUom = productUom;
}
public String getProductImage() {
return productImage;
}
public void setProductImage(String productImage) {
this.productImage = productImage;
}
public String getProductDescription() {
return productDescription;
}
public void setProductDescription(String productDescription) {
this.productDescription = productDescription;
}
public String getProductManufacturer() {
return productManufacturer;
}
public void setProductManufacturer(String productManufacturer) {
this.productManufacturer = productManufacturer;
}
public String getManufacturerId() {
return manufacturerId;
}
public void setManufacturerId(String manufacturerId) {
this.manufacturerId = manufacturerId;
}
public String getReplaceId() {
return replaceId;
}
public void setReplaceId(String replaceId) {
this.replaceId = replaceId;
}
public String getReplaceDate() {
return replaceDate;
}
public void setReplaceDate(String replaceDate) {
this.replaceDate = replaceDate;
}
public String getProductAddedDate() {
return productAddedDate;
}
public void setProductAddedDate(String productAddedDate) {
this.productAddedDate = productAddedDate;
}
public String getProductAddedBy() {
return productAddedBy;
}
public void setProductAddedBy(String productAddedBy) {
this.productAddedBy = productAddedBy;
}
public String getProductModifiedDate() {
return productModifiedDate;
}
public void setProductModifiedDate(String productModifiedDate) {
this.productModifiedDate = productModifiedDate;
}
public String getProductModifiedBy() {
return productModifiedBy;
}
public void setProductModifiedBy(String productModifiedBy) {
this.productModifiedBy = productModifiedBy;
}
public String getProductStatus() {
return productStatus;
}
public void setProductStatus(String productStatus) {
this.productStatus = productStatus;
}
public String getManufacturerName() {
return manufacturerName;
}
public void setManufacturerName(String manufacturerName) {
this.manufacturerName = manufacturerName;
}
public String getContractedId() {
return contractedId;
}
public void setContractedId(String contractedId) {
this.contractedId = contractedId;
}
public List<Object> getDataSheets() {
return dataSheets;
}
public void setDataSheets(List<Object> dataSheets) {
this.dataSheets = dataSheets;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(productId);
parcel.writeString(productOgpmId);
parcel.writeString(productPartNumber);
parcel.writeString(escapePartNumber);
parcel.writeString(productName);
parcel.writeString(productUom);
parcel.writeString(productImage);
parcel.writeString(productDescription);
parcel.writeString(productManufacturer);
parcel.writeString(manufacturerId);
parcel.writeString(replaceId);
parcel.writeString(replaceDate);
parcel.writeString(productAddedDate);
parcel.writeString(productAddedBy);
parcel.writeString(productModifiedDate);
parcel.writeString(productModifiedBy);
parcel.writeString(productStatus);
parcel.writeString(manufacturerName);
parcel.writeString(contractedId);
}
}*/
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException:
Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 24 path
$.data
com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read
Please recheck your data. Maybe it look like bellow
{
"status": true,
"data": [
{
"product_id": "12",
"product_ogpm_id": "OGPR1000485",
"product_part_number": "6ED1 057-1AA01-0BA0",
"escape_part_number": "6ed10571aa010ba0",
"product_name": "USB PC Cable",
"product_uom": "",
"product_image": "",
"product_description": "",
"product_manufacturer": "Siemens",
"manufacturer_id": "4",
"replace_id": "0",
"replace_date": "0000-00-00 00:00:00",
"product_added_date": "2017-09-12 00:57:15",
"product_added_by": "Jayank Chopra",
"product_modified_date": "0000-00-00 00:00:00",
"product_modified_by": "",
"product_status": "1",
"manufacturer_name": "Siemens",
"contracted_id": "1",
"data_sheets": []
},
{
"product_id": "13",
"product_ogpm_id": "OGPR1000485",
"product_part_number": "6ED1 057-1AA01-0BA0",
"escape_part_number": "6ed10571aa010ba0",
"product_name": "USB PC Cable",
"product_uom": "",
"product_image": "",
"product_description": "",
"product_manufacturer": "Siemens",
"manufacturer_id": "4",
"replace_id": "0",
"replace_date": "0000-00-00 00:00:00",
"product_added_date": "2017-09-12 00:57:15",
"product_added_by": "Jayank Chopra",
"product_modified_date": "0000-00-00 00:00:00",
"product_modified_by": "",
"product_status": "1",
"manufacturer_name": "Siemens",
"contracted_id": "1",
"data_sheets": []
}
],
"message": "Product found!"
}
or if it same with you posted
Please make sure the BarcodeSearchResponse look like this:
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class BarcodeSearchResponse {
#SerializedName("status")
#Expose
private boolean status;
#SerializedName("data")
#Expose
private ScanData data;
#SerializedName("message")
#Expose
private String message;
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public ScanData getData() {
return data;
}
public void setData(ScanData data) {
this.data = data;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
Your POJO looks wrong. Your Data Class should look like this.
public class Data {
#SerializedName("product_id")
#Expose
private String productId;
#SerializedName("product_ogpm_id")
#Expose
private String productOgpmId;
#SerializedName("product_part_number")
#Expose
private String productPartNumber;
#SerializedName("escape_part_number")
#Expose
private String escapePartNumber;
#SerializedName("product_name")
#Expose
private String productName;
#SerializedName("product_uom")
#Expose
private String productUom;
#SerializedName("product_image")
#Expose
private String productImage;
#SerializedName("product_description")
#Expose
private String productDescription;
#SerializedName("product_manufacturer")
#Expose
private String productManufacturer;
#SerializedName("manufacturer_id")
#Expose
private String manufacturerId;
#SerializedName("replace_id")
#Expose
private String replaceId;
#SerializedName("replace_date")
#Expose
private String replaceDate;
#SerializedName("product_added_date")
#Expose
private String productAddedDate;
#SerializedName("product_added_by")
#Expose
private String productAddedBy;
#SerializedName("product_modified_date")
#Expose
private String productModifiedDate;
#SerializedName("product_modified_by")
#Expose
private String productModifiedBy;
#SerializedName("product_status")
#Expose
private String productStatus;
#SerializedName("manufacturer_name")
#Expose
private String manufacturerName;
#SerializedName("contracted_id")
#Expose
private String contractedId;
#SerializedName("data_sheets")
#Expose
private List<Object> dataSheets = null;
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public String getProductOgpmId() {
return productOgpmId;
}
public void setProductOgpmId(String productOgpmId) {
this.productOgpmId = productOgpmId;
}
public String getProductPartNumber() {
return productPartNumber;
}
public void setProductPartNumber(String productPartNumber) {
this.productPartNumber = productPartNumber;
}
public String getEscapePartNumber() {
return escapePartNumber;
}
public void setEscapePartNumber(String escapePartNumber) {
this.escapePartNumber = escapePartNumber;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getProductUom() {
return productUom;
}
public void setProductUom(String productUom) {
this.productUom = productUom;
}
public String getProductImage() {
return productImage;
}
public void setProductImage(String productImage) {
this.productImage = productImage;
}
public String getProductDescription() {
return productDescription;
}
public void setProductDescription(String productDescription) {
this.productDescription = productDescription;
}
public String getProductManufacturer() {
return productManufacturer;
}
public void setProductManufacturer(String productManufacturer) {
this.productManufacturer = productManufacturer;
}
public String getManufacturerId() {
return manufacturerId;
}
public void setManufacturerId(String manufacturerId) {
this.manufacturerId = manufacturerId;
}
public String getReplaceId() {
return replaceId;
}
public void setReplaceId(String replaceId) {
this.replaceId = replaceId;
}
public String getReplaceDate() {
return replaceDate;
}
public void setReplaceDate(String replaceDate) {
this.replaceDate = replaceDate;
}
public String getProductAddedDate() {
return productAddedDate;
}
public void setProductAddedDate(String productAddedDate) {
this.productAddedDate = productAddedDate;
}
public String getProductAddedBy() {
return productAddedBy;
}
public void setProductAddedBy(String productAddedBy) {
this.productAddedBy = productAddedBy;
}
public String getProductModifiedDate() {
return productModifiedDate;
}
public void setProductModifiedDate(String productModifiedDate) {
this.productModifiedDate = productModifiedDate;
}
public String getProductModifiedBy() {
return productModifiedBy;
}
public void setProductModifiedBy(String productModifiedBy) {
this.productModifiedBy = productModifiedBy;
}
public String getProductStatus() {
return productStatus;
}
public void setProductStatus(String productStatus) {
this.productStatus = productStatus;
}
public String getManufacturerName() {
return manufacturerName;
}
public void setManufacturerName(String manufacturerName) {
this.manufacturerName = manufacturerName;
}
public String getContractedId() {
return contractedId;
}
public void setContractedId(String contractedId) {
this.contractedId = contractedId;
}
public List<Object> getDataSheets() {
return dataSheets;
}
public void setDataSheets(List<Object> dataSheets) {
this.dataSheets = dataSheets;
}
}
And your ScanData Class should use this Data Class as following.
public class ScanData {
#SerializedName("status")
#Expose
private Boolean status;
#SerializedName("data")
#Expose
private Data data;
#SerializedName("message")
#Expose
private String message;
public Boolean getStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
P.S.
I have not made it parcelable, I guess you can do that by yourself.

Categories

Resources