I'm getting the following error when using an ObjectMapper to de-serialize an object:
JSONMappingException Can not construct instance of
org.springframework.data.Page, problem: abstract types can only be
instantiated with additional type information.
I am trying to serialize a JSON string into a Spring data object org.springframework.data.Page which represents a page of type T.
The User class is a simple POJO with first and last name. The JSON string I am deserializing is:
{
"content": [
{
"firstname": "John",
"lastname": "Doe"
},
{
"firstname": "Jane",
"lastname": "Doe"
}
],
"size": 2,
"number": 0,
"sort": [
{
"direction": "DESC",
"property": "timestamp",
"ascending": false
}
],
"totalPages": 150,
"numberOfElements": 100,
"totalElements": 15000,
"firstPage": true,
"lastPage": false
}
This causes the exception:
Page<User> userPage = (Page<User>) new ObjectMapper().mapToJavaObject(json, new TypeReference<Page<User>>(){};
Since Page is a Spring object I cannot modify it which I think makes this a bit different from the way I see this question asked elsewhere. Any thoughts?
I ended up using something like this, creating a bean as #Perception suggested:
import java.util.ArrayList;
import java.util.List;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
public class PageImplBean<T> extends PageImpl<T> {
private static final long serialVersionUID = 1L;
private int number;
private int size;
private int totalPages;
private int numberOfElements;
private long totalElements;
private boolean previousPage;
private boolean firstPage;
private boolean nextPage;
private boolean lastPage;
private List<T> content;
private Sort sort;
public PageImplBean() {
super(new ArrayList<T>());
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public int getTotalPages() {
return totalPages;
}
public void setTotalPages(int totalPages) {
this.totalPages = totalPages;
}
public int getNumberOfElements() {
return numberOfElements;
}
public void setNumberOfElements(int numberOfElements) {
this.numberOfElements = numberOfElements;
}
public long getTotalElements() {
return totalElements;
}
public void setTotalElements(long totalElements) {
this.totalElements = totalElements;
}
public boolean isPreviousPage() {
return previousPage;
}
public void setPreviousPage(boolean previousPage) {
this.previousPage = previousPage;
}
public boolean isFirstPage() {
return firstPage;
}
public void setFirstPage(boolean firstPage) {
this.firstPage = firstPage;
}
public boolean isNextPage() {
return nextPage;
}
public void setNextPage(boolean nextPage) {
this.nextPage = nextPage;
}
public boolean isLastPage() {
return lastPage;
}
public void setLastPage(boolean lastPage) {
this.lastPage = lastPage;
}
public List<T> getContent() {
return content;
}
public void setContent(List<T> content) {
this.content = content;
}
public Sort getSort() {
return sort;
}
public void setSort(Sort sort) {
this.sort = sort;
}
public PageImpl<T> pageImpl() {
return new PageImpl<T>(getContent(), new PageRequest(getNumber(),
getSize(), getSort()), getTotalElements());
}
}
and then modify your code to use the concrete class and get the PageImpl:
#SuppressWarnings("unchecked")
Page<User> userPage = ((PageImplBean<User>)new ObjectMapper().readValue(json, new TypeReference<PageImplBean<User>>() {})).pageImpl();
You can do this:
public class YourClass {
static class CustomPage extends PageImpl<User> {
#JsonCreator(mode = Mode.PROPERTIES)
public CustomPage(#JsonProperty("content") List<User> content, #JsonProperty("number") int page, #JsonProperty("size") int size, #JsonProperty("totalElements") long total) {
super(content, new PageRequest(page, size), total);
}
}
public Page<User> makeRequest(String json) {
Page<User> pg = new ObjectMapper().readValue(json, CustomPage.class);
return pg;
}
}
Related
Model classes looks like this MailFilterCondition has map of EmailCondition where Filter is a class and MailAttributes and Operator are enums:
public class EmailCondition implements Serializable {
private static final long serialVersionUID = -5429392022485346125L;
private Filter.MailAttributes key;
private Filter.Operator op;
private String value;
public Filter.MailAttributes getKey() {
return key;
}
public void setKey(Filter.MailAttributes key) {
this.key = key;
}
public Operator getOp() {
return op;
}
public void setOp(Operator op) {
this.op = op;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
#Override
public String toString() {
return "EmailCondition [key=" + key + ", op=" + op + ", value=" + value + "]";
}
}
public class MailFilterCondition implements Serializable {
private static final long serialVersionUID = -2691329267596354267L;
private int automationId;
private Map<String, EmailCondition> emailConditionMap;
private String filterString;
public int getAutomationId() {
return automationId;
}
public void setAutomationId(int automationId) {
this.automationId = automationId;
}
public Map<String, EmailCondition> getEmailConditions() {
return emailConditionMap;
}
public void setEmailConditions(Map<String, EmailCondition> emailConditionMap) {
this.emailConditionMap = emailConditionMap;
}
public String getFilterString() {
return filterString;
}
public void setFilterString(String filterString) {
this.filterString = filterString;
}
#Override
public String toString() {
return "MailFilterCondition [automationId=" + automationId + ", emailConditions=" + emailConditionMap
+ ", filterString=" + filterString + "]";
}
}
Controller:
#PostMapping(value = "/email")
public void createAutomationFilter(#RequestParam(value="automation_id") int automationId, #RequestBody MailFilterCondition filterData) {
System.out.println(filterData);
}
Request body:
{
"automationId": 123,
"filterString": "(c1_and_c2)_or_(c1_and_c3)",
"emailConditionMap":
{
"c1":{
"key": "from",
"op": "contains",
"value": "jhon"
},
"c2":{
"key": "from1",
"op": "starts",
"value": "ron"
},
"c3":{
"key": "from",
"op": "contains",
"value": "payment"
}
}
}
Filter enums:
public class Filter {
public enum Operator {
contains("contains"), starts("starts"), ends("ends"), gt("gt"), gteq("gteq"), lt("lt"), lteq("lteq"), eq("eq"),
inlist("inlist"), pattern("pattern");
private final String operator;
private Operator(String opt) {
this.operator = opt;
}
public String getValue() {
return this.operator;
}
}
public enum MailAttributes {
from("from"), to("to"), subject("subject"), body("body"), received_time("received_time");
private final String attribute;
private MailAttributes(String attribute) {
this.attribute = attribute;
}
public String getValue() {
return this.attribute;
}
}
public enum LogicOperator {
AND("_and_"), OR("_or_");
private final String operator;
private LogicOperator(String opt) {
this.operator = opt;
}
public String getValue() {
return this.operator;
}
}
}
Output:
MailFilterCondition [automationId=123, emailConditions=null, filterString=(c1_and_c2)_or_(c1_and_c3)]
While passing key-value pair in json the map attribute reamins null. I tried everything but every-time emailConditions prints null.
Do you have proper getters/setters in the classes?
I am not sure what the Filter class is, but changing those two fields to String it is working perfectly. So the problem may be there.
You need to use Jackson Marshalling. It will convert the object automatically before being sent in the request body.
Jackson uses getters and setters so your object must have them.
#PostMapping(value = "/email")
public void createAutomationFilter(#RequestParam(value="automation_id") int automationId, #RequestBody MailFilterCondition filterData) {
System.out.println(filterData);
}
Here in createAutomationFilter method you are passing #RequestParam(value="automation_id") int automationId as parameter, which is not correct as you sending all parameter in request body in Postman. So you have to map all parameter in one Model class (i.e MailFilterCondition) and by using
#RequestBody annotation. Please see the below controller.
Controller:
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
#RequestMapping(value = "/mail")
public class TestController {
#PostMapping(value = "/create", produces = { "application/json" })
public void createAutomationFilter(#RequestBody final MailFilterCondition emailConditionMap,
final HttpServletRequest request) {
System.out.println(emailConditionMap);
}
}
In this model MailFilterCondition your setter and getter for emailConditionMap field is not appropiate.
public Map<String, EmailCondition> getEmailConditions() {
return emailConditionMap;
}
public void setEmailConditions(Map<String, EmailCondition> emailConditionMap) {
this.emailConditionMap = emailConditionMap;
}
Update your setter and getter with (Spring used to map fields with exactly the same name of the field setters)
public Map<String, EmailCondition> getEmailConditionMap() {
return emailConditionMap;
}
public void setEmailConditionMap(Map<String, EmailCondition>
emailConditionMap) {
this.emailConditionMap = emailConditionMap;
}
Model: MailFilterCondition
import java.io.Serializable;
import java.util.Map;
public class MailFilterCondition implements Serializable {
private static final long serialVersionUID = -2691329267596354267L;
private int automationId;
private Map<String, EmailCondition> emailConditionMap;
private String filterString;
public int getAutomationId() {
return automationId;
}
public void setAutomationId(int automationId) {
this.automationId = automationId;
}
public Map<String, EmailCondition> getEmailConditionMap() {
return emailConditionMap;
}
public void setEmailConditionMap(Map<String, EmailCondition> emailConditionMap) {
this.emailConditionMap = emailConditionMap;
}
public String getFilterString() {
return filterString;
}
public void setFilterString(String filterString) {
this.filterString = filterString;
}
#Override
public String toString() {
return "MailFilterCondition [automationId=" + automationId + ", emailConditions=" + emailConditionMap
+ ", filterString=" + filterString + "]";
}
}
In model EmailCondition, i am passing String as param in
public void setKey(String key) {
this.key = Filter.MailAttributes.valueOf(key);
}
public void setOp(String op) {
this.op = Filter.Operator.valueOf(op);
}
as you can see in request body you are passing key and op value as String,
these value are not any kind of custom java class. At run time Spring could not figure out the type, which you passing
public void setKey(Filter.MailAttributes key) {
this.key = key;
}
public void setOp(Operator op) {
this.op = op;
}
as per my knowledge, you can also bind these fields using #InitBinder annotation.
Model: EmailCondition
import java.io.Serializable;
import com.spring.web.controller.Filter.MailAttributes;
import com.spring.web.controller.Filter.Operator;
public class EmailCondition implements Serializable {
private static final long serialVersionUID = -5429392022485346125L;
private Filter.MailAttributes key;
private Filter.Operator op;
private String value;
public void setKey(String key) {
this.key = Filter.MailAttributes.valueOf(key);
}
public void setOp(String op) {
this.op = Filter.Operator.valueOf(op);
}
public void setValue(String value) {
this.value = value;
}
public MailAttributes getKey() {
return key;
}
public Operator getOp() {
return op;
}
public String getValue() {
return value;
}
#Override
public String toString() {
return "EmailCondition [key=" + key + ", op=" + op + ", value=" + value + "]";
}
}
Model: Filter
public class Filter {
public enum Operator {
contains("contains"), starts("starts"), ends("ends"), gt("gt"), gteq("gteq"), lt("lt"), lteq("lteq"), eq(
"eq"), inlist("inlist"), pattern("pattern");
private final String operator;
private Operator(String opt) {
this.operator = opt;
}
public String getValue() {
return this.operator;
}
}
public enum MailAttributes {
from("from"), to("to"), subject("subject"), body("body"), received_time("received_time");
private final String attribute;
private MailAttributes(String attribute) {
this.attribute = attribute;
}
public String getValue() {
return this.attribute;
}
}
public enum LogicOperator {
AND("_and_"), OR("_or_");
private final String operator;
private LogicOperator(String opt) {
this.operator = opt;
}
public String getValue() {
return this.operator;
}
}
}
You can send ajax request as below:
var payLoad = {
"automationId": 123,
"filterString": "(c1_and_c2)_or_(c1_and_c3)",
"emailConditionMap":
{
"c1":{
"key": "from",
"op": "contains",
"value": "jhon"
},
"c2":{
"key": "to",
"op": "starts",
"value": "ron"
},
"c3":{
"key": "subject",
"op": "ends",
"value": "payment"
}
}
};
$.ajax({
url: appContextJs+"/mail/create",
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(payLoad),
success: callbackfunction
});
appContextJs: as your base URL e.g: http://localhost:8080/webapp
Please do not forget to set contentType as application/json in Postman
Postman console output:
{
"automationId": 123,
"emailConditionMap": {
"c1": {
"key": "from",
"op": "contains",
"value": "jhon"
},
"c2": {
"key": "to",
"op": "starts",
"value": "ron"
},
"c3": {
"key": "subject",
"op": "ends",
"value": "payment"
}
},
"filterString": "(c1_and_c2)_or_(c1_and_c3)"
}
Eclipse console output:
MailFilterCondition [automationId=123, emailConditions={c1=EmailCondition [key=from, op=contains, value=jhon], c2=EmailCondition [key=to, op=starts, value=ron], c3=EmailCondition [key=subject, op=ends, value=payment]}, filterString=(c1_and_c2)_or_(c1_and_c3)]
My JSON string.
{
"RateCardType": [{
"rate_id": 32,
"applianceId": 59,
"categoryId": 33,
"install_Price": 599,
"uninstall_Price": 0,
"gasRefill_Price": 0,
"repair_Price": 249,
"basicClean_Price": 0,
"deepClean_Price": 449,
"demo_Price": 500
},
{
"rate_id": 33,
"applianceId": 59,
"categoryId": 34,
"install_Price": 799,
"uninstall_Price": 0,
"gasRefill_Price": 0,
"repair_Price": 349,
"basicClean_Price": 0,
"deepClean_Price": 799,
"demo_Price": 500
}
]
}
MyRateCard.java
package com.example.demo;
import javax.persistence.Column;
public class MyRateCard {
#Column(name = "rate_id")
int rate_id;
public void setRate_id(int rate_id) {
this.rate_id=rate_id;
}
public int getRate_id() {
return rate_id;
}
#Column(name = "applianceId")
int applianceId;
public void setApplianceId(int applianceId {
this.applianceId=applianceId;
}
public int getApplianceId() {
return applianceId;
}
#Column(name = "categoryId")
int categoryId;
public void setCategoryId(int categoryId) {
this.categoryId=categoryId;
}
public int getCategoryId() {
return categoryId;
}
#Column(name = "install_Price")
int install_Price;
public void setInstall_Price(int install_Price {
this.install_Price=install_Price;
}
public int getInstall_Price() {
return install_Price;
}
#Column(name = "uninstall_Price")
int uninstall_Price;
public void setUninstall_Price(int uninstall_Price) {
this.uninstall_Price=uninstall_Price;
}
public int getUninstall_Price() {
return uninstall_Price;
}
#Column(name = "gasRefill_Price")
int gasRefill_Price;
public void setGasRefill_Price(int gasRefill_Price) {
this.gasRefill_Price=gasRefill_Price;
}
public int getGasRefill_Price() {
return gasRefill_Price;
}
#Column(name = "repair_Price")
int repair_Price;
public void setRepair_Price(int repair_Price) {
this.repair_Price=repair_Price;
}
public int getRepair_Price() {
return repair_Price;
}
#Column(name = "basicClean_Price")
int basicClean_Price;
public void setBasicClean_Price(int basicClean_Price) {
this.basicClean_Price=basicClean_Price;
}
public int getBasicClean_Price() {
return basicClean_Price;
}
#Column(name = "deepClean_Price")
int deepClean_Price;
public void setDeepClean_Price(int deepClean_price) {
this.deepClean_Price=deepClean_price;
}
public int getDeepClean_Price() {
return deepClean_Price;
}
#Column(name = "demo_Price")
int demo_Price;
public void setDemo_Price(int demo_Price) {
this.demo_Price=demo_Price;
}
public int getDemo_Price() {
return demo_Price;
}
}
I have created a model class MyRateCard.java with all getters and setters. I want to create a object for MyRateCard with first object in JSON string(say rate_id:32).
MyRateCard ratecard = new Gson().fromJson(response.toString(), MyRateCard.class);
But not working. Can someone help me to parse this?
{
"RateCardType": [{
"rate_id": 32,
"applianceId": 59,
"categoryId": 33,
"install_Price": 599,
"uninstall_Price": 0,
"gasRefill_Price": 0,
"repair_Price": 249,
"basicClean_Price": 0,
"deepClean_Price": 449,
"demo_Price": 500
},
{
"rate_id": 33,
"applianceId": 59,
"categoryId": 34,
"install_Price": 799,
"uninstall_Price": 0,
"gasRefill_Price": 0,
"repair_Price": 349,
"basicClean_Price": 0,
"deepClean_Price": 799,
"demo_Price": 500
}
]
}
This is your JSON. This is JSON is an Object which contains an array of RateCardType.
You have created the RateCardType class.
Now create a class which consists of List of MyRateCard class.
class ListRateCard {
List<MyRateCard> RateCardType;
// write getter and setter
}
Now, write the below code:
ListRateCard ratecards = new Gson().fromJson(response.toString(), ListRateCard.class);
Fetch rateId by the below code:
ratecards.getRateCardType().get(0).getRate_id();
These are 2 files.The MyPojo class is a holder for your actual data.In your json as you can the outer {} signifies an object,this object contains just 1 key called RateCardType.Hence the outer class called MyPojo.
Now the key RateCardType contains a list of objects as shown by the [] brackets,hence the List<RateCardType> .The rest is just data contained within the RateCardType class which you had got initially.
public class MyPojo
{
private List<RateCardType> RateCardType;
public List<RateCardType> getRateCardType ()
{
return RateCardType;
}
public void setRateCardType (List<RateCardType> RateCardType)
{
this.RateCardType = RateCardType;
}
}
public class RateCardType
{
private String repair_Price;
private String basicClean_Price;
private String uninstall_Price;
private String categoryId;
private String install_Price;
private String rate_id;
private String gasRefill_Price;
private String demo_Price;
private String deepClean_Price;
private String applianceId;
public String getRepair_Price ()
{
return repair_Price;
}
public void setRepair_Price (String repair_Price)
{
this.repair_Price = repair_Price;
}
public String getBasicClean_Price ()
{
return basicClean_Price;
}
public void setBasicClean_Price (String basicClean_Price)
{
this.basicClean_Price = basicClean_Price;
}
public String getUninstall_Price ()
{
return uninstall_Price;
}
public void setUninstall_Price (String uninstall_Price)
{
this.uninstall_Price = uninstall_Price;
}
public String getCategoryId ()
{
return categoryId;
}
public void setCategoryId (String categoryId)
{
this.categoryId = categoryId;
}
public String getInstall_Price ()
{
return install_Price;
}
public void setInstall_Price (String install_Price)
{
this.install_Price = install_Price;
}
public String getRate_id ()
{
return rate_id;
}
public void setRate_id (String rate_id)
{
this.rate_id = rate_id;
}
public String getGasRefill_Price ()
{
return gasRefill_Price;
}
public void setGasRefill_Price (String gasRefill_Price)
{
this.gasRefill_Price = gasRefill_Price;
}
public String getDemo_Price ()
{
return demo_Price;
}
public void setDemo_Price (String demo_Price)
{
this.demo_Price = demo_Price;
}
public String getDeepClean_Price ()
{
return deepClean_Price;
}
public void setDeepClean_Price (String deepClean_Price)
{
this.deepClean_Price = deepClean_Price;
}
public String getApplianceId ()
{
return applianceId;
}
public void setApplianceId (String applianceId)
{
this.applianceId = applianceId;
}
}
In order to use it
MyPojo holder= new Gson().fromJson(response.toString(), MyPojo.class);
List<RateCardType> list=holder.getRateCardType();
for(int i=0;i<list.size();i++)
{
list.get(i).getBasicClean_Price();
....
}
you can access any json level by tree hierachy
MyRateCard ratecard = new Gson().fromJson(response.toString(), MyRateCard.class);
String rateid=ratecard.rate_id;
I'm using retrofit 2 for networking functions in my project, and I'm able to parse the json object responses from the server but now I'm supposed to parse a json array that look like this
[
{
"id_asset": 1,
"id_category": 1,
"id_brand": 2,
"name": "Samsung Galaxy 6",
"status": 1,
"updated_at": "Oct 3, 2016 10:24:28 AM",
"rank": 1,
"rate": {
"id_asset_rate": 2,
"id_asset": 1,
"value": 5000,
"loan_to_value": 50,
"offered": 2500,
"annual_rate": 3,
"quantity": 5,
"created_at": "Oct 23, 2016 5:31:31 AM",
"updated_at": "Oct 23, 2016 5:32:31 AM"
},
"best_rate": {
"id_asset": "1",
"value": "5000",
"loan_to_value": "50",
"offered": "2500",
"annual_rate": "3",
"quantity": "5",
"rank": "1"
},
"category": {
"id_category": 1,
"id_parent": 0,
"name": "Mobile Phones",
"image": "",
"sort": 1,
"status": 1,
"created_at": null,
"updated_at": null,
"_links": {
"self": {
"href": "/v1/categories/1"
}
}
},
"brand": {
"id_brand": 2,
"name": "Samsung",
"status": 1,
"created_at": null,
"updated_at": null
},
"_links": {
"self": {
"href": "/v1/assets/1"
}
}
},
{
"id_asset": 2,
"id_category": 1,
"id_brand": 1,
"name": "i Phone 5",
"status": 1,
"updated_at": "Oct 3, 2016 8:04:36 AM",
"rank": false,
"rate": null,
"best_rate": false,
"category": {
"id_category": 1,
"id_parent": 0,
"name": "Mobile Phones",
"image": "",
"sort": 1,
"status": 1,
"created_at": null,
"updated_at": null,
"_links": {
"self": {
"href": "/v1/categories/1"
}
}
},
"brand": {
"id_brand": 1,
"name": "Apple",
"status": 1,
"created_at": null,
"updated_at": null
},
"_links": {
"self": {
"href": "/v1/assets/2"
}
}
}
]
This is the response from the server and I created this POJO for the response
public class AssetResponse {
private Integer id_asset;
private Integer id_category;
private Integer id_brand;
private String name;
private Integer status;
private String updated_at;
private AssetRate assetRate;
private AssetCategory assetCategory;
private Links links;
private Self self;
private AssetBrand assetBrand;
private HasLinked hasLinked;
public Integer getId_asset() {
return id_asset;
}
public void setId_asset(Integer id_asset) {
this.id_asset = id_asset;
}
public Integer getId_category() {
return id_category;
}
public void setId_category(Integer id_category) {
this.id_category = id_category;
}
public Integer getId_brand() {
return id_brand;
}
public void setId_brand(Integer id_brand) {
this.id_brand = id_brand;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getUpdated_at() {
return updated_at;
}
public void setUpdated_at(String updated_at) {
this.updated_at = updated_at;
}
public AssetRate getAssetRate() {
return assetRate;
}
public void setAssetRate(AssetRate assetRate) {
this.assetRate = assetRate;
}
public AssetCategory getAssetCategory() {
return assetCategory;
}
public void setAssetCategory(AssetCategory assetCategory) {
this.assetCategory = assetCategory;
}
public Links getLinks() {
return links;
}
public void setLinks(Links links) {
this.links = links;
}
public Self getSelf() {
return self;
}
public void setSelf(Self self) {
this.self = self;
}
public AssetBrand getAssetBrand() {
return assetBrand;
}
public void setAssetBrand(AssetBrand assetBrand) {
this.assetBrand = assetBrand;
}
public HasLinked getHasLinked() {
return hasLinked;
}
public void setHasLinked(HasLinked hasLinked) {
this.hasLinked = hasLinked;
}
private class AssetRate {
private Integer id_asset_rate;
private Integer id_asset;
private Double value;
private Double loan_to_value;
private Double offered;
private Double annual_rate;
private String updated_at;
public Integer getId_asset_rate() {
return id_asset_rate;
}
public void setId_asset_rate(Integer id_asset_rate) {
this.id_asset_rate = id_asset_rate;
}
public Integer getId_asset() {
return id_asset;
}
public void setId_asset(Integer id_asset) {
this.id_asset = id_asset;
}
public Double getValue() {
return value;
}
public void setValue(Double value) {
this.value = value;
}
public Double getLoan_to_value() {
return loan_to_value;
}
public void setLoan_to_value(Double loan_to_value) {
this.loan_to_value = loan_to_value;
}
public Double getOffered() {
return offered;
}
public void setOffered(Double offered) {
this.offered = offered;
}
public Double getAnnual_rate() {
return annual_rate;
}
public void setAnnual_rate(Double annual_rate) {
this.annual_rate = annual_rate;
}
public String getUpdated_at() {
return updated_at;
}
public void setUpdated_at(String updated_at) {
this.updated_at = updated_at;
}
}
private class AssetCategory {
private Integer id_category;
private Integer id_parent;
private String name;
private String image;
private Integer sort;
private Integer status;
private String created_at;
private String updated_at;
private Links links;
public Integer getId_category() {
return id_category;
}
public void setId_category(Integer id_category) {
this.id_category = id_category;
}
public Integer getId_parent() {
return id_parent;
}
public void setId_parent(Integer id_parent) {
this.id_parent = id_parent;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public Integer getSort() {
return sort;
}
public void setSort(Integer sort) {
this.sort = sort;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getCreated_at() {
return created_at;
}
public void setCreated_at(String created_at) {
this.created_at = created_at;
}
public String getUpdated_at() {
return updated_at;
}
public void setUpdated_at(String updated_at) {
this.updated_at = updated_at;
}
public Links getLinks() {
return links;
}
public void setLinks(Links links) {
this.links = links;
}
}
private class Links {
#SerializedName("self")
#Expose
private Self self;
/**
*
* #return
* The self
*/
public Self getSelf() {
return self;
}
/**
*
* #param self
* The self
*/
public void setSelf(Self self) {
this.self = self;
}
}
private class Self {
#SerializedName("href")
#Expose
private String href;
/**
*
* #return
* The href
*/
public String getHref() {
return href;
}
/**
*
* #param href
* The href
*/
public void setHref(String href) {
this.href = href;
}
}
private class AssetBrand {
private Integer id_brand;
private String name;
private Integer status;
private String created_at;
private String updated_at;
public Integer getId_brand() {
return id_brand;
}
public void setId_brand(Integer id_brand) {
this.id_brand = id_brand;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getCreated_at() {
return created_at;
}
public void setCreated_at(String created_at) {
this.created_at = created_at;
}
public String getUpdated_at() {
return updated_at;
}
public void setUpdated_at(String updated_at) {
this.updated_at = updated_at;
}
}
private class HasLinked {
private Integer has_linked;
private Links links;
public Integer getHas_linked() {
return has_linked;
}
public void setHas_linked(Integer has_linked) {
this.has_linked = has_linked;
}
public Links getLinks() {
return links;
}
public void setLinks(Links links) {
this.links = links;
}
}
}
}
Is my pojo is right ?
My problem is, I can't parse this response. Any help will be appreciated.
Thanks in advance
EDIT :
This is my request to server (using rest api)
#GET("url")
Call<AssetResponse> getAssetList();
EDIT 2: I've changed the code to List, as suggested by Niko Adrianus Yuwono.
This is the new changes
private void getAssets() {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(logging);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient.build())
.build();
final ApiInterface apiInterface = retrofit.create(ApiInterface.class);
final AssetRequest assetRequest = new AssetRequest();
assetRequest.setAcc_tok(ACCESS_TOKEN);
final Call<List<AssetResponse>> assetList = apiInterface.getAssetList();
assetList.enqueue(new Callback <List<AssetResponse>>() {
#Override
public void onResponse(Call<List<AssetResponse>> call, Response<List<AssetResponse>> response) {
int statusCode = response.code();
List<AssetResponse> assetResponseList = response.body();
if (statusCode == 200) {
for (int i = 0; i < assetResponseList.size(); i++ ){
Integer id_asset = assetResponseList.get(i).getId_asset();
Integer id_category = assetResponseList.get(i).getId_category();
Integer status = assetResponseList.get(i).getStatus();
String name = assetResponseList.get(i).getName();
Log.d("Assets ","Asset id_asset bb : " + id_asset);
Log.d("Assets ","Asset id_category bb : " + id_category);
Log.d("Assets ","Asset name bb : " + name);
Log.d("Assets ","Asset status bb : " + status);
Double val = assetResponseList.get(i).getAssetRate().getValue();
Log.d("val ","val is : " +val);
}
} else {
Toast.makeText(getContext(), "network error " + statusCode, Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<List<AssetResponse>> call, Throwable t) {
Log.d("Asset GET Failure", "onFailure: " + t.getMessage());
//showProgress(false);
}
});
}
and this is the response from the server
D/Assets: Asset id_asset bb : 1 D/Assets: Asset id_category bb : 1 D/Assets: Asset name bb : Samsung Galaxy 6 D/Assets: Asset status
bb : 1 10-26 13:13:17.898 22784-22784/ D/AndroidRuntime: Shutting down
VM 10-26 13:13:17.898 22784-22784/ E/AndroidRuntime: FATAL EXCEPTION:
main Process: , PID: 22784 java.lang.NullPointerException: Attempt to
invoke virtual method 'java.lang.Double
.api.model.AssetResponse$AssetRate.getValue()' on a null object
reference
.AssetDatabaseFragment$2.onResponse(AssetDatabaseFragment.java:133)
retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:68)
android.os.Handler.handleCallback(Handler.java:739)
android.os.Handler.dispatchMessage(Handler.java:95)
android.os.Looper.loop(Looper.java:148)
android.app.ActivityThread.main(ActivityThread.java:5417)
java.lang.reflect.Method.invoke(Native Method)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Whenever I access the inner objects it throws error like the above
Your POJO looks right, but your JSON response is a JSONArray so you need to declare it as a List of Objects rather than an Object
#GET("url")
Call<List<AssetResponse>> getAssetList();
And you need to change your inner class access to public so GSON can see the setter and getter of that class.
Your Json key value data is changing from one index to another.
Wrong Json:
[{
//Make this either integer or boolean
"rank": 1,
// best rate is object here in the next index, it's treated as boolean.
"best_rate": {
"id_asset": "1",
"value": "5000",
"loan_to_value": "50",
"offered": "2500",
"annual_rate": "3",
"quantity": "5",
"rank": "1"
}
},
{
"rank":false,
"best_rate":false,
}
]
I have a complete project shared on github with your json.
https://github.com/lingarajsankaravelu/retrofit2v.git
Retrofit code should be like this as i mentioned in the question comment.
#GET("url")
Call<List<AssetResponse>> getAssetList();
As you have requested to explain the changes in your pojo class it should be like this.
AssetReponse.class:
public class AssetResponse {
private Integer id_asset;
private Integer id_category;
private Integer id_brand;
private String name;
private Integer status;
private String updated_at;
private AssetRate assetRate;
private AssetCategory assetCategory;
private Links links;
private Self self;
private AssetBrand assetBrand;
private HasLinked hasLinked;
public Integer getId_asset() {
return id_asset;
}
public void setId_asset(Integer id_asset) {
this.id_asset = id_asset;
}
public Integer getId_category() {
return id_category;
}
public void setId_category(Integer id_category) {
this.id_category = id_category;
}
public Integer getId_brand() {
return id_brand;
}
public void setId_brand(Integer id_brand) {
this.id_brand = id_brand;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getUpdated_at() {
return updated_at;
}
public void setUpdated_at(String updated_at) {
this.updated_at = updated_at;
}
public AssetRate getAssetRate() {
return assetRate;
}
public void setAssetRate(AssetRate assetRate) {
this.assetRate = assetRate;
}
public AssetCategory getAssetCategory() {
return assetCategory;
}
public void setAssetCategory(AssetCategory assetCategory) {
this.assetCategory = assetCategory;
}
public Links getLinks() {
return links;
}
public void setLinks(Links links) {
this.links = links;
}
public Self getSelf() {
return self;
}
public void setSelf(Self self) {
this.self = self;
}
public AssetBrand getAssetBrand() {
return assetBrand;
}
public void setAssetBrand(AssetBrand assetBrand) {
this.assetBrand = assetBrand;
}
public HasLinked getHasLinked() {
return hasLinked;
}
public void setHasLinked(HasLinked hasLinked) {
this.hasLinked = hasLinked;
}
}
AssetRate.class
public class AssetRate {
private Integer id_asset_rate;
private Integer id_asset;
private Double value;
private Double loan_to_value;
private Double offered;
private Double annual_rate;
private String updated_at;
public Integer getId_asset_rate() {
return id_asset_rate;
}
public void setId_asset_rate(Integer id_asset_rate) {
this.id_asset_rate = id_asset_rate;
}
public Integer getId_asset() {
return id_asset;
}
public void setId_asset(Integer id_asset) {
this.id_asset = id_asset;
}
public Double getValue() {
return value;
}
public void setValue(Double value) {
this.value = value;
}
public Double getLoan_to_value() {
return loan_to_value;
}
public void setLoan_to_value(Double loan_to_value) {
this.loan_to_value = loan_to_value;
}
public Double getOffered() {
return offered;
}
public void setOffered(Double offered) {
this.offered = offered;
}
public Double getAnnual_rate() {
return annual_rate;
}
public void setAnnual_rate(Double annual_rate) {
this.annual_rate = annual_rate;
}
public String getUpdated_at() {
return updated_at;
}
public void setUpdated_at(String updated_at) {
this.updated_at = updated_at;
}
}
Seperate your inner class like above. Seperating your inner class model will be useful if you are working on a large project. where you don't have to write the same pojo class again. you can use this seperate class structure instead.
You can use this site to generate POJO class. Just enter your JSON response and choose which JSON type you using like GSON,Jackson.etc. and You get perfect POJO classes. no need to change anything.
http://www.jsonschema2pojo.org/
Your Retrofit interface should be
#GET("url")
Call<List<AssetReponse>> getAssessList();
And make sure that your variable name same with key on JSON Response Or you can use annotation #SerializedName for that & for make it simple you can use JSON to POJO Online converter : http://www.jsonschema2pojo.org/
When i am trying Parce this json data with GSON. I am unable to get JsonArray in side of JsonObject. Below is my code, every suggestion will get appriciated.
JSON DATA FROM SERVER :
{
"GetJobDetails": {
"MaxAmount": 0,
"CreatorId": 1,
"JobImages": [
{
"ImagePath": "http://192.168.1.108:8088/Uploads/6e660c0c-4a2b- 42dc-ad97-82cc3efe87a0.jpg",
"JobImageId": 1
},
{
"ImagePath": "http://192.168.1.108:8088/Uploads/ccf1087d-9f7e-4c21-bc61-8aa3fd924e05.jpg",
"JobImageId": 2
},
{
"ImagePath": "http://192.168.1.108:8088/Uploads/4333e8b6-0079-457f-a225-fd7900ea81b1.jpg",
"JobImageId": 3
}
],
}
}
In ACTIVITY :
Gson gson = new Gson();
String response = new String(mresponce);
JobDetails jobDetails= gson.fromJson(response, JobDetails .class);
Log.e("JobDetails ",""+jobDetails.getJobImagesList());
this log prints allways null even when i have images list there in my data.
MODEL CLASS :
public class JobDetails implements Parcelable {
private int MaxAmount;
private int CreatorId;
private List<JobImage> JobImages;
public JobDetails() {
}
public JobDetails(Parcel parcel) {
this.MaxAmount = parcel.readInt();
this.CreatorId= parcel.readInt();
this.JobImages = new ArrayList<JobImage>();
parcel.readTypedList(JobImages, JobImage.CREATOR);
}
// Parcelable
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(this.MaxAmount);
dest.writeInt(this.CreatorId);
dest.writeList(this.JobImages);
// TODO: Not Parceling AddressList
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public JobDetails createFromParcel(Parcel in) {
return new JobDetails(in);
}
public JobDetails[] newArray(int size) {
return new JobDetails[size];
}
};
public List<JobImage> getJobImagesList() {
return JobImages;
}
public void setJobImagesList(List<JobImage> jobImages) {
JobImages = jobImages;
}
public int getMaxAmount() {
return MaxAmount;
}
public void setMaxAmount(int maxAmount) {
MaxAmount= maxAmount;
}
}
ANOTHER MODEL CLASS FOR JOBIMAGE:
public class JobImage implements Parcelable {
private String ImagePath;
private int JobImageId;
JobImage(){
}
public JobImage(Parcel in) {
this.ImagePath = in.readString();
this.JobImageId = in.readInt();
}
// Parcelable
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.ImagePath);
dest.writeInt(this.JobImageId);
// TODO: Not Parceling AddressList
}
public static final Creator CREATOR = new Creator() {
public JobImage createFromParcel(Parcel in) {
return new JobImage(in);
}
public JobImage[] newArray(int size) {
return new JobImage[size];
}
};
public String getImagePath() {
return ImagePath;
}
public void setImagePath(String imagePath) {
ImagePath = imagePath;
}
public int getJobImageId() {
return JobImageId;
}
public void setJobImageId(int jobImageId) {
JobImageId = jobImageId;
}
}
Please help me to find what i am doing wrong in this :
Your top-level JSON object is not a JobDetails object, it is an object that has JobDetails member name GetJobDetails. You need to handle this level of your JSON. You can do it with a custom TypeAdapter, or perhaps easier, just make a container object and deserialize it.
class JobDetailContainer {
private JobDetails GetJobDetails;
public JobDetails getJobDetails() {
return GetJobDetails;
}
}
then use --
Gson gson = new Gson();
String response = new String(mresponce);
GetJobDetails getJobDetails= gson.fromJson(response, GetJobDetails.class);
Log.e("JobDetails ",""+getJobDetails.getJobDetails().getJobImagesList());
Agreed with #iagreen ...I should handel top level json object too..this is what i have done after doing some R&D
public class GetJobDetails {
public GetJobDetailsResult getGetJobDetailsResult() {
return GetJobDetailsResult;
}
public void setGetJobDetailsResult(GetJobDetailsResult GetJobDetailsResult) {
this.GetJobDetailsResult = GetJobDetailsResult;
}
}
For Inner Json :
public class GetJobDetailsResult {
private Integer MaxAmount;
private Integer CreatorTotJobPosted;
private List<JobImage> JobImages = new ArrayList<JobImage>();
public Integer getMaxAmount() {
return MaxAmount;
}
public void setMaxAmount(Integer MaxAmount) {
this.MaxAmount = MaxAmount;
}
public Integer getCreatorTotJobPosted() {
return CreatorTotJobPosted;
}
public void setCreatorTotJobPosted(Integer CreatorTotJobPosted) {
this.CreatorTotJobPosted = CreatorTotJobPosted;
}
public List<JobImage> getJobImages() {
return JobImages;
}
public void setJobImages(List<JobImage> JobImages) {
this.JobImages = JobImages;
}
}
Finally For To Hold JobImages
public class JobImage {
private String ImagePath;
private Integer JobImageId;
public String getImagePath() {
return ImagePath;
}
public void setImagePath(String ImagePath) {
this.ImagePath = ImagePath;
}
public Integer getJobImageId() {
return JobImageId;
}
public void setJobImageId(Integer JobImageId) {
this.JobImageId = JobImageId;
}
}
Final Step :
Gson gson = new Gson();
String response = new String(jsonObjectresponce.toString());
GetJobDetails getJobDetails = gson.fromJson(response, GetJobDetails.class);
GetJobDetailsResult result = getJobDetails.getGetJobDetailsResult();
// now result object contains my json data.
I am trying to read the below json data. How to read using LinkedTreeMap?
{"msgType": "gameInit", "data": {
"race": {
"track": {
"id": "indianapolis",
"name": "Indianapolis",
"pieces": [
{
"length": 100.0
},
{
"length": 100.0,
"switch": true
},
{
"radius": 200,
"angle": 22.5
}
],
"lanes": [
{
"distanceFromCenter": -20,
"index": 0
},
{
"distanceFromCenter": 0,
"index": 1
},
{
"distanceFromCenter": 20,
"index": 2
}
],
"startingPoint": {
"position": {
"x": -340.0,
"y": -96.0
},
"angle": 90.0
}
},
"cars": [
{
"id": {
"name": "Schumacher",
"color": "red"
},
"dimensions": {
"length": 40.0,
"width": 20.0,
"guideFlagPosition": 10.0
}
},
{
"id": {
"name": "Rosberg",
"color": "blue"
},
"dimensions": {
"length": 40.0,
"width": 20.0,
"guideFlagPosition": 10.0
}
}
],
"raceSession": {
"laps": 3,
"maxLapTimeMs": 30000,
"quickRace": true
}
}
}}
I've little long but working approach to parse your JSON Object using Gson.
You can try it as following:
import com.google.gson.Gson;
public class JsonParser {
public static void main(String[] args){
Gson gson = new Gson();
String yourJson = "";
MainObject object = gson.fromJson(yourJson, MainObject.class);
}
}
Here yourJson is your JSON object in which your response is received, here I've used String just to show you.
And MainObject is the POJO for required to parse your JSON object.
I've shown all POJOs for that are required for your JSON. Try to use it.
MainObject.java
public class MainObject {
private String msgType;
private Data data;
public String getMsgType() {
return msgType;
}
public void setMsgType(String msgType) {
this.msgType = msgType;
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
}
Data.java
public class Data {
private race race;
public race getRace() {
return race;
}
public void setRace(race race) {
this.race = race;
}
}
Track.java
public class Track{
private String id;
private String name;
private List<Pieces> pieces;
private List<Lanes> lanes;
private startingPoint startingPoint;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Pieces> getPieces() {
return pieces;
}
public void setPieces(List<Pieces> pieces) {
this.pieces = pieces;
}
public List<Lanes> getLanes() {
return lanes;
}
public void setLanes(List<Lanes> lanes) {
this.lanes = lanes;
}
public startingPoint getStartingPoint() {
return startingPoint;
}
public void setStartingPoint(startingPoint startingPoint) {
this.startingPoint = startingPoint;
}
}
Pieces.java
public class Pieces{
private int length;
private boolean switch;
private int radius;
private float angle;
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public int getRadius() {
return radius;
}
public void setRadius(int radius) {
this.radius = radius;
}
public float getAngle() {
return angle;
}
public void setAngle(float angle) {
this.angle = angle;
}
public boolean isSwitch() {
return Switch;
}
public void setSwitch(boolean _switch) {
Switch = _switch;
}
}
Lanes.java
public class Lanes{
private String distanceFromCenter;
private int index;
public String getDistanceFromCenter() {
return distanceFromCenter;
}
public void setDistanceFromCenter(String distanceFromCenter) {
this.distanceFromCenter = distanceFromCenter;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
}
StartingPoint.java
public class StartingPoint{
private String angle;
private Position position;
public String getAngle() {
return angle;
}
public void setAngle(String angle) {
this.angle = angle;
}
public Position getPosition() {
return position;
}
public void setPosition(Position position) {
this.position = position;
}
}
Position.java
public class Position{
private String x;
private String y;
public String getX() {
return x;
}
public void setX(String x) {
this.x = x;
}
public String getY() {
return y;
}
public void setY(String y) {
this.y = y;
}
}
Cars.java
public class Cars{
private Id id;
private Dimensions dimensions;
public id getId() {
return id;
}
public void setId(id id) {
this.id = id;
}
public Dimensions getDimensions() {
return dimensions;
}
public void setDimensions(Dimensions dimensions) {
this.dimensions = dimensions;
}
}
Id.java
public class Id{
private String name;
private String color;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
Dimensions.java
public class Dimensions{
private int length;
private int width;
private int guideFlagPosition;
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getGuideFlagPosition() {
return guideFlagPosition;
}
public void setGuideFlagPosition(int guideFlagPosition) {
this.guideFlagPosition = guideFlagPosition;
}
}
RaceSession.java
public class RaceSession{
private int lap;
private String maxLapTimeMs;
private boolean quickRace;
public int getLap() {
return lap;
}
public void setLap(int lap) {
this.lap = lap;
}
public String getMaxLapTimeMs() {
return maxLapTimeMs;
}
public void setMaxLapTimeMs(String maxLapTimeMs) {
this.maxLapTimeMs = maxLapTimeMs;
}
public boolean isQuickRace() {
return quickRace;
}
public void setQuickRace(boolean quickRace) {
this.quickRace = quickRace;
}
}
That's all. All required POJOs are here.
I've used this approach and it's working fine.
From the site:
public static void main(String[] args) {
Gson gson = new Gson();
try {
System.out.println("Reading JSON from a file");
System.out.println("----------------------------");
BufferedReader br = new BufferedReader(
new FileReader(args[0]));
//convert the json string back to object
MyBean countryObj = gson.fromJson(br, MyBean.class);
// MyBean contains the data in the JSON and is a standard Java Bean
}
}
BufferedReader in = new BufferedReader(input);
String inputLine;
String fullline = "";
while ((inputLine = in.readLine()) != null) {
fullline = fullline.concat(inputLine);
}
JSONObject rootObject = new JSONObject(fullline);
JSONObject rows1 = rootObject.getJSONObject("data");
JSONObject race = rows1.getJSONObject("race");
JSONObject track = rows1.getJSONObject("track");
JSONArray pieces = rows1.getJSONArray("pieces");
Hello This is simple you can do using JSON there is no need to use external library Gson.it can also increase the your app size.so avoid to use it.
// Try to parse JSON
try {
JSONObject jsonObjMain = new JSONObject(myjsonstring);
JSONObject jsonObjectData=(JSONObject) jsonObjMain.get("data");
JSONObject jsonObjectRace=(JSONObject) jsonObjectData.get("race");
JSONObject jsonObjectTrack=(JSONObject) jsonObjectRace.get("track");
JSONArray jsonArrayPieces=(JSONArray) jsonObjectTrack.get("pieces");
JSONArray jsonArrayLanes=(JSONArray) jsonObjectTrack.get("lanes");
JSONObject jsonObjectStartingPoint=(JSONObject) jsonObjectTrack.get("startingPoint");
System.out.println("Starting Point :"+jsonObjectStartingPoint);
JSONArray jsonArrayCars=(JSONArray) jsonObjectRace.get("cars");
JSONObject jsonObjectRaceSession=(JSONObject) jsonObjectRace.get("raceSession");
System.out.println("Race Session :"+jsonObjectRaceSession);
for (int i = 0; i < jsonArrayCars.length(); i++) {
JSONObject jsonObj = jsonArrayCars.getJSONObject(i);
JSONObject jsonObjId = (JSONObject) jsonObj.get("id");
System.out.println("id :"+jsonObjId);
JSONObject jsonObjDimensions = (JSONObject) jsonObj.get("dimensions");
System.out.println("Dinmentions :"+jsonObjDimensions);
}
for (int i = 0; i < jsonArrayPieces.length(); i++) {
JSONObject jsonObj = jsonArrayPieces.getJSONObject(i);
System.out.println("Piece data :"+jsonObj);
}
for (int i = 0; i < jsonArrayLanes.length(); i++) {
JSONObject jsonObj = jsonArrayLanes.getJSONObject(i);
System.out.println("Lanes data :"+jsonObj);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}