I'm using Pocket API to get a list of bookmarked articles and their URLs, there are hundreds, here is a sample with only 2 articles:
{
"status": 1,
"complete": 1,
"list": {
"734233858": {
"item_id": "734233858",
"resolved_id": "734233858",
"given_url": "https://blog.openshift.com/developing-single-page-web-applications-using-java-8-spark-mongodb-and-angularjs/",
"given_title": "",
"favorite": "0",
"status": "0",
"time_added": "1466459879",
"time_updated": "1466459862",
"time_read": "0",
"time_favorited": "0",
"sort_id": 1,
"resolved_title": "Developing Single Page Web Applications using Java 8, Spark, MongoDB, and AngularJS",
"resolved_url": "https://blog.openshift.com/developing-single-page-web-applications-using-java-8-spark-mongodb-and-angularjs/",
"excerpt": "In this post you will learn how to use a micro framework called Spark to build a RESTful backend. The RESTful backend is consumed by a single page web application using AngularJS and MongoDB for data storage. I’ll also show you how to run Java 8 on OpenShift.",
"is_article": "1",
"is_index": "0",
"has_video": "0",
"has_image": "1",
"word_count": "2727"
},
"1015284226": {
"item_id": "1015284226",
"resolved_id": "1015284226",
"given_url": "https://sparktutorials.github.io/2015/08/04/spark-video-tutorials.html",
"given_title": "",
"favorite": "0",
"status": "0",
"time_added": "1466458750",
"time_updated": "1466458737",
"time_read": "0",
"time_favorited": "0",
"sort_id": 0,
"resolved_title": "Spark Video Tutorials",
"resolved_url": "http://sparktutorials.github.io/2015/08/04/spark-video-tutorials.html",
"excerpt": "Our friends over at learnhowtoprogram.com have been working on a series of Java courses for beginners, all of which feature Spark. This post contains an overview of these courses with direct links to their videos.",
"is_article": "1",
"is_index": "0",
"has_video": "0",
"has_image": "0",
"word_count": "41"
}
},
"error": null,
"search_meta": {
"search_type": "normal"
},
"since": 1509309762
}
As you can see the "list": {} has many items, but it's an array, it contains objects. So when I try to generate the POJOs using http://www.jsonschema2pojo.org I get POJOS named after each item's ID :
package model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class _1015284226 {
#SerializedName("item_id")
#Expose
private String itemId;
#SerializedName("resolved_id")
#Expose
private String resolvedId;
#SerializedName("given_url")
#Expose
private String givenUrl;
#SerializedName("given_title")
#Expose
private String givenTitle;
#SerializedName("favorite")
#Expose
private String favorite;
#SerializedName("status")
#Expose
private String status;
#SerializedName("time_added")
#Expose
private String timeAdded;
#SerializedName("time_updated")
#Expose
private String timeUpdated;
#SerializedName("time_read")
#Expose
private String timeRead;
#SerializedName("time_favorited")
#Expose
private String timeFavorited;
#SerializedName("sort_id")
#Expose
private Integer sortId;
#SerializedName("resolved_title")
#Expose
private String resolvedTitle;
#SerializedName("resolved_url")
#Expose
private String resolvedUrl;
#SerializedName("excerpt")
#Expose
private String excerpt;
#SerializedName("is_article")
#Expose
private String isArticle;
#SerializedName("is_index")
#Expose
private String isIndex;
#SerializedName("has_video")
#Expose
private String hasVideo;
#SerializedName("has_image")
#Expose
private String hasImage;
#SerializedName("word_count")
#Expose
private String wordCount;
/**
* No args constructor for use in serialization
*
*/
public _1015284226() {
}
/**
*
* #param hasImage
* #param givenUrl
* #param status
* #param timeFavorited
* #param isIndex
* #param excerpt
* #param resolvedId
* #param sortId
* #param givenTitle
* #param timeUpdated
* #param isArticle
* #param wordCount
* #param itemId
* #param favorite
* #param timeAdded
* #param hasVideo
* #param resolvedUrl
* #param resolvedTitle
* #param timeRead
*/
public _1015284226(String itemId, String resolvedId, String givenUrl, String givenTitle, String favorite, String status, String timeAdded, String timeUpdated, String timeRead, String timeFavorited, Integer sortId, String resolvedTitle, String resolvedUrl, String excerpt, String isArticle, String isIndex, String hasVideo, String hasImage, String wordCount) {
super();
this.itemId = itemId;
this.resolvedId = resolvedId;
this.givenUrl = givenUrl;
this.givenTitle = givenTitle;
this.favorite = favorite;
this.status = status;
this.timeAdded = timeAdded;
this.timeUpdated = timeUpdated;
this.timeRead = timeRead;
this.timeFavorited = timeFavorited;
this.sortId = sortId;
this.resolvedTitle = resolvedTitle;
this.resolvedUrl = resolvedUrl;
this.excerpt = excerpt;
this.isArticle = isArticle;
this.isIndex = isIndex;
this.hasVideo = hasVideo;
this.hasImage = hasImage;
this.wordCount = wordCount;
}
public String getItemId() {
return itemId;
}
public void setItemId(String itemId) {
this.itemId = itemId;
}
public String getResolvedId() {
return resolvedId;
}
public void setResolvedId(String resolvedId) {
this.resolvedId = resolvedId;
}
public String getGivenUrl() {
return givenUrl;
}
public void setGivenUrl(String givenUrl) {
this.givenUrl = givenUrl;
}
public String getGivenTitle() {
return givenTitle;
}
public void setGivenTitle(String givenTitle) {
this.givenTitle = givenTitle;
}
public String getFavorite() {
return favorite;
}
public void setFavorite(String favorite) {
this.favorite = favorite;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getTimeAdded() {
return timeAdded;
}
public void setTimeAdded(String timeAdded) {
this.timeAdded = timeAdded;
}
public String getTimeUpdated() {
return timeUpdated;
}
public void setTimeUpdated(String timeUpdated) {
this.timeUpdated = timeUpdated;
}
public String getTimeRead() {
return timeRead;
}
public void setTimeRead(String timeRead) {
this.timeRead = timeRead;
}
public String getTimeFavorited() {
return timeFavorited;
}
public void setTimeFavorited(String timeFavorited) {
this.timeFavorited = timeFavorited;
}
public Integer getSortId() {
return sortId;
}
public void setSortId(Integer sortId) {
this.sortId = sortId;
}
public String getResolvedTitle() {
return resolvedTitle;
}
public void setResolvedTitle(String resolvedTitle) {
this.resolvedTitle = resolvedTitle;
}
public String getResolvedUrl() {
return resolvedUrl;
}
public void setResolvedUrl(String resolvedUrl) {
this.resolvedUrl = resolvedUrl;
}
public String getExcerpt() {
return excerpt;
}
public void setExcerpt(String excerpt) {
this.excerpt = excerpt;
}
public String getIsArticle() {
return isArticle;
}
public void setIsArticle(String isArticle) {
this.isArticle = isArticle;
}
public String getIsIndex() {
return isIndex;
}
public void setIsIndex(String isIndex) {
this.isIndex = isIndex;
}
public String getHasVideo() {
return hasVideo;
}
public void setHasVideo(String hasVideo) {
this.hasVideo = hasVideo;
}
public String getHasImage() {
return hasImage;
}
public void setHasImage(String hasImage) {
this.hasImage = hasImage;
}
public String getWordCount() {
return wordCount;
}
public void setWordCount(String wordCount) {
this.wordCount = wordCount;
}
}
the List POJO which contains the items was created as:
package model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class List {
#SerializedName("1015284226")
#Expose
private model._1015284226 _1015284226;
/**
* No args constructor for use in serialization
*
*/
public List() {
}
/**
*
* #param _1015284226
*/
public List(model._1015284226 _1015284226) {
super();
this._1015284226 = _1015284226;
}
public model._1015284226 get1015284226() {
return _1015284226;
}
public void set1015284226(model._1015284226 _1015284226) {
this._1015284226 = _1015284226;
}
}
which is obviously giving me issues when I try to parse the JSON
I'm using retrofit 2 .
I'm thinking I should refactor the List POJO so it contains an ArrayList of items, but don't want to fiddle too much with what was automatically generated for me.
You can do it manually like this.
JSONObject jsonObj = new JSONObject(json);
JSONObject lists= jsonObj.getJSONObject("list");
Iterator x = lists.keys();
JSONArray jsonArray = new JSONArray();
while (x.hasNext()){
String key = (String) x.next();
jsonArray.put(lists.get(key));
}
jsonArray is your list.
After that, you may parse JSON to object.
Related
I am getting list of coins from API https://min-api.cryptocompare.com/data/all/coinlist?api-key.
It returns json response like this -
{
"Response": "Success",
"Message": "Coin list succesfully returned!",
"Data": {
"42": {
"Id": "4321",
"Url": "/coins/42/overview",
"ImageUrl": "/media/35650717/42.jpg",
"ContentCreatedOn": 1427211129,
"Name": "42",
"Symbol": "42",
"CoinName": "42 Coin",
"FullName": "42 Coin (42)",
"Algorithm": "Scrypt",
"ProofType": "PoW/PoS",
"FullyPremined": "0",
"TotalCoinSupply": "42",
"BuiltOn": "N/A",
"SmartContractAddress": "N/A",
"DecimalPlaces": 0,
"PreMinedValue": "N/A",
"TotalCoinsFreeFloat": "N/A",
"SortOrder": "34",
"Sponsored": false,
"Taxonomy": {
"Access": "",
"FCA": "",
"FINMA": "",
"Industry": "",
"CollateralizedAsset": "",
"CollateralizedAssetType": "",
"CollateralType": "",
"CollateralInfo": ""
},
"Rating": {
"Weiss": {
"Rating": "",
"TechnologyAdoptionRating": "",
"MarketPerformanceRating": ""
}
},
"IsTrading": true,
"TotalCoinsMined": 41.9999528,
"BlockNumber": 173122,
"NetHashesPerSecond": 0,
"BlockReward": 0,
"BlockTime": 0
},
"300": {
"Id": "749869",
"Url": "/coins/300/overview",
"ImageUrl": "/media/27010595/300.png",
"ContentCreatedOn": 1517935016,
"Name": "300",
"Symbol": "300",
"CoinName": "300 token",
"FullName": "300 token (300)",
"Algorithm": "N/A",
"ProofType": "N/A",
"FullyPremined": "0",
"TotalCoinSupply": "300",
"BuiltOn": "7605",
"SmartContractAddress": "0xaec98a708810414878c3bcdf46aad31ded4a4557",
"DecimalPlaces": 18,
"PreMinedValue": "N/A",
"TotalCoinsFreeFloat": "N/A",
"SortOrder": "2212",
"Sponsored": false,
"Taxonomy": {
"Access": "",
"FCA": "",
"FINMA": "",
"Industry": "",
"CollateralizedAsset": "",
"CollateralizedAssetType": "",
"CollateralType": "",
"CollateralInfo": ""
},
"Rating": {
"Weiss": {
"Rating": "",
"TechnologyAdoptionRating": "",
"MarketPerformanceRating": ""
}
},
"IsTrading": true,
"TotalCoinsMined": 300,
"BlockNumber": 0,
"NetHashesPerSecond": 0,
"BlockReward": 0,
"BlockTime": 0
}
}
}
When I am generating pojo class for it, it is creating class _42 as well as class _300 means for every object it is creating new class.
Here it is :-
package com.mountblue.cryptocoin.entity;
import com.google.gson.annotations.SerializedName;
public class CoinBean {
/**
* Response : Success
* Message : Coin list succesfully returned!
* Data : {"42":{"Id":"4321","Url":"/coins/42/overview","ImageUrl":"/media/35650717/42.jpg","ContentCreatedOn":1427211129,"Name":"42","Symbol":"42","CoinName":"42 Coin","FullName":"42 Coin (42)","Algorithm":"Scrypt","ProofType":"PoW/PoS","FullyPremined":"0","TotalCoinSupply":"42","BuiltOn":"N/A","SmartContractAddress":"N/A","DecimalPlaces":0,"PreMinedValue":"N/A","TotalCoinsFreeFloat":"N/A","SortOrder":"34","Sponsored":false,"Taxonomy":{"Access":"","FCA":"","FINMA":"","Industry":"","CollateralizedAsset":"","CollateralizedAssetType":"","CollateralType":"","CollateralInfo":""},"Rating":{"Weiss":{"Rating":"","TechnologyAdoptionRating":"","MarketPerformanceRating":""}},"IsTrading":true,"TotalCoinsMined":41.9999528,"BlockNumber":173122,"NetHashesPerSecond":0,"BlockReward":0,"BlockTime":0},"300":{"Id":"749869","Url":"/coins/300/overview","ImageUrl":"/media/27010595/300.png","ContentCreatedOn":1517935016,"Name":"300","Symbol":"300","CoinName":"300 token","FullName":"300 token (300)","Algorithm":"N/A","ProofType":"N/A","FullyPremined":"0","TotalCoinSupply":"300","BuiltOn":"7605","SmartContractAddress":"0xaec98a708810414878c3bcdf46aad31ded4a4557","DecimalPlaces":18,"PreMinedValue":"N/A","TotalCoinsFreeFloat":"N/A","SortOrder":"2212","Sponsored":false,"Taxonomy":{"Access":"","FCA":"","FINMA":"","Industry":"","CollateralizedAsset":"","CollateralizedAssetType":"","CollateralType":"","CollateralInfo":""},"Rating":{"Weiss":{"Rating":"","TechnologyAdoptionRating":"","MarketPerformanceRating":""}},"IsTrading":true,"TotalCoinsMined":300,"BlockNumber":0,"NetHashesPerSecond":0,"BlockReward":0,"BlockTime":0}}
*/
private String Response;
private String Message;
private DataBean Data;
public String getResponse() {
return Response;
}
public void setResponse(String Response) {
this.Response = Response;
}
public String getMessage() {
return Message;
}
public void setMessage(String Message) {
this.Message = Message;
}
public DataBean getData() {
return Data;
}
public void setData(DataBean Data) {
this.Data = Data;
}
public static class DataBean {
/**
* 42 : {"Id":"4321","Url":"/coins/42/overview","ImageUrl":"/media/35650717/42.jpg","ContentCreatedOn":1427211129,"Name":"42","Symbol":"42","CoinName":"42 Coin","FullName":"42 Coin (42)","Algorithm":"Scrypt","ProofType":"PoW/PoS","FullyPremined":"0","TotalCoinSupply":"42","BuiltOn":"N/A","SmartContractAddress":"N/A","DecimalPlaces":0,"PreMinedValue":"N/A","TotalCoinsFreeFloat":"N/A","SortOrder":"34","Sponsored":false,"Taxonomy":{"Access":"","FCA":"","FINMA":"","Industry":"","CollateralizedAsset":"","CollateralizedAssetType":"","CollateralType":"","CollateralInfo":""},"Rating":{"Weiss":{"Rating":"","TechnologyAdoptionRating":"","MarketPerformanceRating":""}},"IsTrading":true,"TotalCoinsMined":41.9999528,"BlockNumber":173122,"NetHashesPerSecond":0,"BlockReward":0,"BlockTime":0}
* 300 : {"Id":"749869","Url":"/coins/300/overview","ImageUrl":"/media/27010595/300.png","ContentCreatedOn":1517935016,"Name":"300","Symbol":"300","CoinName":"300 token","FullName":"300 token (300)","Algorithm":"N/A","ProofType":"N/A","FullyPremined":"0","TotalCoinSupply":"300","BuiltOn":"7605","SmartContractAddress":"0xaec98a708810414878c3bcdf46aad31ded4a4557","DecimalPlaces":18,"PreMinedValue":"N/A","TotalCoinsFreeFloat":"N/A","SortOrder":"2212","Sponsored":false,"Taxonomy":{"Access":"","FCA":"","FINMA":"","Industry":"","CollateralizedAsset":"","CollateralizedAssetType":"","CollateralType":"","CollateralInfo":""},"Rating":{"Weiss":{"Rating":"","TechnologyAdoptionRating":"","MarketPerformanceRating":""}},"IsTrading":true,"TotalCoinsMined":300,"BlockNumber":0,"NetHashesPerSecond":0,"BlockReward":0,"BlockTime":0}
*/
#SerializedName("42")
private _$42Bean _$42;
#SerializedName("300")
private _$300Bean _$300;
public _$42Bean get_$42() {
return _$42;
}
public void set_$42(_$42Bean _$42) {
this._$42 = _$42;
}
public _$300Bean get_$300() {
return _$300;
}
public void set_$300(_$300Bean _$300) {
this._$300 = _$300;
}
public static class _$42Bean {
/**
* Id : 4321
* Url : /coins/42/overview
* ImageUrl : /media/35650717/42.jpg
* ContentCreatedOn : 1427211129
* Name : 42
* Symbol : 42
* CoinName : 42 Coin
* FullName : 42 Coin (42)
* Algorithm : Scrypt
* ProofType : PoW/PoS
* FullyPremined : 0
* TotalCoinSupply : 42
* BuiltOn : N/A
* SmartContractAddress : N/A
* DecimalPlaces : 0
* PreMinedValue : N/A
* TotalCoinsFreeFloat : N/A
* SortOrder : 34
* Sponsored : false
* Taxonomy : {"Access":"","FCA":"","FINMA":"","Industry":"","CollateralizedAsset":"","CollateralizedAssetType":"","CollateralType":"","CollateralInfo":""}
* Rating : {"Weiss":{"Rating":"","TechnologyAdoptionRating":"","MarketPerformanceRating":""}}
* IsTrading : true
* TotalCoinsMined : 41.9999528
* BlockNumber : 173122
* NetHashesPerSecond : 0
* BlockReward : 0
* BlockTime : 0
*/
private String Id;
private String Url;
private String ImageUrl;
private int ContentCreatedOn;
private String Name;
private String Symbol;
private String CoinName;
private String FullName;
private String Algorithm;
private String ProofType;
private String FullyPremined;
private String TotalCoinSupply;
private String BuiltOn;
private String SmartContractAddress;
private int DecimalPlaces;
private String PreMinedValue;
private String TotalCoinsFreeFloat;
private String SortOrder;
private boolean Sponsored;
private TaxonomyBean Taxonomy;
private RatingBean Rating;
private boolean IsTrading;
private double TotalCoinsMined;
private int BlockNumber;
private int NetHashesPerSecond;
private int BlockReward;
private int BlockTime;
public String getId() {
return Id;
}
public void setId(String Id) {
this.Id = Id;
}
public String getUrl() {
return Url;
}
public void setUrl(String Url) {
this.Url = Url;
}
public String getImageUrl() {
return ImageUrl;
}
public void setImageUrl(String ImageUrl) {
this.ImageUrl = ImageUrl;
}
public int getContentCreatedOn() {
return ContentCreatedOn;
}
public void setContentCreatedOn(int ContentCreatedOn) {
this.ContentCreatedOn = ContentCreatedOn;
}
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public String getSymbol() {
return Symbol;
}
public void setSymbol(String Symbol) {
this.Symbol = Symbol;
}
public String getCoinName() {
return CoinName;
}
public void setCoinName(String CoinName) {
this.CoinName = CoinName;
}
public String getFullName() {
return FullName;
}
public void setFullName(String FullName) {
this.FullName = FullName;
}
public String getAlgorithm() {
return Algorithm;
}
public void setAlgorithm(String Algorithm) {
this.Algorithm = Algorithm;
}
public String getProofType() {
return ProofType;
}
public void setProofType(String ProofType) {
this.ProofType = ProofType;
}
public String getFullyPremined() {
return FullyPremined;
}
public void setFullyPremined(String FullyPremined) {
this.FullyPremined = FullyPremined;
}
public String getTotalCoinSupply() {
return TotalCoinSupply;
}
public void setTotalCoinSupply(String TotalCoinSupply) {
this.TotalCoinSupply = TotalCoinSupply;
}
public String getBuiltOn() {
return BuiltOn;
}
public void setBuiltOn(String BuiltOn) {
this.BuiltOn = BuiltOn;
}
public String getSmartContractAddress() {
return SmartContractAddress;
}
public void setSmartContractAddress(String SmartContractAddress) {
this.SmartContractAddress = SmartContractAddress;
}
public int getDecimalPlaces() {
return DecimalPlaces;
}
public void setDecimalPlaces(int DecimalPlaces) {
this.DecimalPlaces = DecimalPlaces;
}
public String getPreMinedValue() {
return PreMinedValue;
}
public void setPreMinedValue(String PreMinedValue) {
this.PreMinedValue = PreMinedValue;
}
public String getTotalCoinsFreeFloat() {
return TotalCoinsFreeFloat;
}
public void setTotalCoinsFreeFloat(String TotalCoinsFreeFloat) {
this.TotalCoinsFreeFloat = TotalCoinsFreeFloat;
}
public String getSortOrder() {
return SortOrder;
}
public void setSortOrder(String SortOrder) {
this.SortOrder = SortOrder;
}
public boolean isSponsored() {
return Sponsored;
}
public void setSponsored(boolean Sponsored) {
this.Sponsored = Sponsored;
}
public TaxonomyBean getTaxonomy() {
return Taxonomy;
}
public void setTaxonomy(TaxonomyBean Taxonomy) {
this.Taxonomy = Taxonomy;
}
public RatingBean getRating() {
return Rating;
}
public void setRating(RatingBean Rating) {
this.Rating = Rating;
}
public boolean isIsTrading() {
return IsTrading;
}
public void setIsTrading(boolean IsTrading) {
this.IsTrading = IsTrading;
}
public double getTotalCoinsMined() {
return TotalCoinsMined;
}
public void setTotalCoinsMined(double TotalCoinsMined) {
this.TotalCoinsMined = TotalCoinsMined;
}
public int getBlockNumber() {
return BlockNumber;
}
public void setBlockNumber(int BlockNumber) {
this.BlockNumber = BlockNumber;
}
public int getNetHashesPerSecond() {
return NetHashesPerSecond;
}
public void setNetHashesPerSecond(int NetHashesPerSecond) {
this.NetHashesPerSecond = NetHashesPerSecond;
}
public int getBlockReward() {
return BlockReward;
}
public void setBlockReward(int BlockReward) {
this.BlockReward = BlockReward;
}
public int getBlockTime() {
return BlockTime;
}
public void setBlockTime(int BlockTime) {
this.BlockTime = BlockTime;
}
public static class TaxonomyBean {
/**
* Access :
* FCA :
* FINMA :
* Industry :
* CollateralizedAsset :
* CollateralizedAssetType :
* CollateralType :
* CollateralInfo :
*/
private String Access;
private String FCA;
private String FINMA;
private String Industry;
private String CollateralizedAsset;
private String CollateralizedAssetType;
private String CollateralType;
private String CollateralInfo;
public String getAccess() {
return Access;
}
public void setAccess(String Access) {
this.Access = Access;
}
public String getFCA() {
return FCA;
}
public void setFCA(String FCA) {
this.FCA = FCA;
}
public String getFINMA() {
return FINMA;
}
public void setFINMA(String FINMA) {
this.FINMA = FINMA;
}
public String getIndustry() {
return Industry;
}
public void setIndustry(String Industry) {
this.Industry = Industry;
}
public String getCollateralizedAsset() {
return CollateralizedAsset;
}
public void setCollateralizedAsset(String CollateralizedAsset) {
this.CollateralizedAsset = CollateralizedAsset;
}
public String getCollateralizedAssetType() {
return CollateralizedAssetType;
}
public void setCollateralizedAssetType(String CollateralizedAssetType) {
this.CollateralizedAssetType = CollateralizedAssetType;
}
public String getCollateralType() {
return CollateralType;
}
public void setCollateralType(String CollateralType) {
this.CollateralType = CollateralType;
}
public String getCollateralInfo() {
return CollateralInfo;
}
public void setCollateralInfo(String CollateralInfo) {
this.CollateralInfo = CollateralInfo;
}
}
public static class RatingBean {
/**
* Weiss : {"Rating":"","TechnologyAdoptionRating":"","MarketPerformanceRating":""}
*/
private WeissBean Weiss;
public WeissBean getWeiss() {
return Weiss;
}
public void setWeiss(WeissBean Weiss) {
this.Weiss = Weiss;
}
public static class WeissBean {
/**
* Rating :
* TechnologyAdoptionRating :
* MarketPerformanceRating :
*/
private String Rating;
private String TechnologyAdoptionRating;
private String MarketPerformanceRating;
public String getRating() {
return Rating;
}
public void setRating(String Rating) {
this.Rating = Rating;
}
public String getTechnologyAdoptionRating() {
return TechnologyAdoptionRating;
}
public void setTechnologyAdoptionRating(String TechnologyAdoptionRating) {
this.TechnologyAdoptionRating = TechnologyAdoptionRating;
}
public String getMarketPerformanceRating() {
return MarketPerformanceRating;
}
public void setMarketPerformanceRating(String MarketPerformanceRating) {
this.MarketPerformanceRating = MarketPerformanceRating;
}
}
}
}
public static class _$300Bean {
/**
* Id : 749869
* Url : /coins/300/overview
* ImageUrl : /media/27010595/300.png
* ContentCreatedOn : 1517935016
* Name : 300
* Symbol : 300
* CoinName : 300 token
* FullName : 300 token (300)
* Algorithm : N/A
* ProofType : N/A
* FullyPremined : 0
* TotalCoinSupply : 300
* BuiltOn : 7605
* SmartContractAddress : 0xaec98a708810414878c3bcdf46aad31ded4a4557
* DecimalPlaces : 18
* PreMinedValue : N/A
* TotalCoinsFreeFloat : N/A
* SortOrder : 2212
* Sponsored : false
* Taxonomy : {"Access":"","FCA":"","FINMA":"","Industry":"","CollateralizedAsset":"","CollateralizedAssetType":"","CollateralType":"","CollateralInfo":""}
* Rating : {"Weiss":{"Rating":"","TechnologyAdoptionRating":"","MarketPerformanceRating":""}}
* IsTrading : true
* TotalCoinsMined : 300
* BlockNumber : 0
* NetHashesPerSecond : 0
* BlockReward : 0
* BlockTime : 0
*/
private String Id;
private String Url;
private String ImageUrl;
private int ContentCreatedOn;
private String Name;
private String Symbol;
private String CoinName;
private String FullName;
private String Algorithm;
private String ProofType;
private String FullyPremined;
private String TotalCoinSupply;
private String BuiltOn;
private String SmartContractAddress;
private int DecimalPlaces;
private String PreMinedValue;
private String TotalCoinsFreeFloat;
private String SortOrder;
private boolean Sponsored;
private TaxonomyBeanX Taxonomy;
private RatingBeanX Rating;
private boolean IsTrading;
private int TotalCoinsMined;
private int BlockNumber;
private int NetHashesPerSecond;
private int BlockReward;
private int BlockTime;
public String getId() {
return Id;
}
public void setId(String Id) {
this.Id = Id;
}
public String getUrl() {
return Url;
}
public void setUrl(String Url) {
this.Url = Url;
}
public String getImageUrl() {
return ImageUrl;
}
public void setImageUrl(String ImageUrl) {
this.ImageUrl = ImageUrl;
}
public int getContentCreatedOn() {
return ContentCreatedOn;
}
public void setContentCreatedOn(int ContentCreatedOn) {
this.ContentCreatedOn = ContentCreatedOn;
}
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public String getSymbol() {
return Symbol;
}
public void setSymbol(String Symbol) {
this.Symbol = Symbol;
}
public String getCoinName() {
return CoinName;
}
public void setCoinName(String CoinName) {
this.CoinName = CoinName;
}
public String getFullName() {
return FullName;
}
public void setFullName(String FullName) {
this.FullName = FullName;
}
public String getAlgorithm() {
return Algorithm;
}
public void setAlgorithm(String Algorithm) {
this.Algorithm = Algorithm;
}
public String getProofType() {
return ProofType;
}
public void setProofType(String ProofType) {
this.ProofType = ProofType;
}
public String getFullyPremined() {
return FullyPremined;
}
public void setFullyPremined(String FullyPremined) {
this.FullyPremined = FullyPremined;
}
public String getTotalCoinSupply() {
return TotalCoinSupply;
}
public void setTotalCoinSupply(String TotalCoinSupply) {
this.TotalCoinSupply = TotalCoinSupply;
}
public String getBuiltOn() {
return BuiltOn;
}
public void setBuiltOn(String BuiltOn) {
this.BuiltOn = BuiltOn;
}
public String getSmartContractAddress() {
return SmartContractAddress;
}
public void setSmartContractAddress(String SmartContractAddress) {
this.SmartContractAddress = SmartContractAddress;
}
public int getDecimalPlaces() {
return DecimalPlaces;
}
public void setDecimalPlaces(int DecimalPlaces) {
this.DecimalPlaces = DecimalPlaces;
}
public String getPreMinedValue() {
return PreMinedValue;
}
public void setPreMinedValue(String PreMinedValue) {
this.PreMinedValue = PreMinedValue;
}
public String getTotalCoinsFreeFloat() {
return TotalCoinsFreeFloat;
}
public void setTotalCoinsFreeFloat(String TotalCoinsFreeFloat) {
this.TotalCoinsFreeFloat = TotalCoinsFreeFloat;
}
public String getSortOrder() {
return SortOrder;
}
public void setSortOrder(String SortOrder) {
this.SortOrder = SortOrder;
}
public boolean isSponsored() {
return Sponsored;
}
public void setSponsored(boolean Sponsored) {
this.Sponsored = Sponsored;
}
public TaxonomyBeanX getTaxonomy() {
return Taxonomy;
}
public void setTaxonomy(TaxonomyBeanX Taxonomy) {
this.Taxonomy = Taxonomy;
}
public RatingBeanX getRating() {
return Rating;
}
public void setRating(RatingBeanX Rating) {
this.Rating = Rating;
}
public boolean isIsTrading() {
return IsTrading;
}
public void setIsTrading(boolean IsTrading) {
this.IsTrading = IsTrading;
}
public int getTotalCoinsMined() {
return TotalCoinsMined;
}
public void setTotalCoinsMined(int TotalCoinsMined) {
this.TotalCoinsMined = TotalCoinsMined;
}
public int getBlockNumber() {
return BlockNumber;
}
public void setBlockNumber(int BlockNumber) {
this.BlockNumber = BlockNumber;
}
public int getNetHashesPerSecond() {
return NetHashesPerSecond;
}
public void setNetHashesPerSecond(int NetHashesPerSecond) {
this.NetHashesPerSecond = NetHashesPerSecond;
}
public int getBlockReward() {
return BlockReward;
}
public void setBlockReward(int BlockReward) {
this.BlockReward = BlockReward;
}
public int getBlockTime() {
return BlockTime;
}
public void setBlockTime(int BlockTime) {
this.BlockTime = BlockTime;
}
......//
}
}
}
I want json to be in Array response. How can I do this?
ApiService class looks like -
#GET("/data/all/coinlist")
Call<CoinBean> getCurrencyList(
#Query("api_key") String apiKey
);
u can create below class structure to de serialize at ur side.
Class Data {
List<Map<String, ImageInfo>> body = new ArrayList()
}
Ok, So I read a couple other questions with this same error, but none have been answered as working, and doesnt seem like I can get it working.
I am connecting to google in-app billing and have everything set up, but, when I try to pull my skudetails (I have 2 SKUs there now), I get the error -
Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $
I have a SubscriptionActivity, Result (serializable), and Details model class (serializable). Below is the code, any help will be great, thanks-
From subscriptionactivity:
Gson gson = new Gson();
try {
Result result = gson.fromJson(skuDetailsList.toString(), Result.class);
if (result != null) {
for (Details d : result.getDetails()) {
System.out.println(d.getProductId()
+ " \n " + d.getTitle() + " \n " + d.getDescription() + " \n "
+ d.getPrice());
}
}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
From details model:
public class Details implements Serializable{
#SerializedName("productId")
#Expose
private String productId;
#SerializedName("type")
#Expose
private String type;
#SerializedName("price")
#Expose
private String price;
#SerializedName("price_amount_micros")
#Expose
private Integer priceAmountMicros;
#SerializedName("price_currency_code")
#Expose
private String priceCurrencyCode;
#SerializedName("subscriptionPeriod")
#Expose
private String subscriptionPeriod;
#SerializedName("freeTrialPeriod")
#Expose
private String freeTrialPeriod;
#SerializedName("title")
#Expose
private String title;
#SerializedName("description")
#Expose
private String description;
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public Integer getPriceAmountMicros() {
return priceAmountMicros;
}
public void setPriceAmountMicros(Integer priceAmountMicros) {
this.priceAmountMicros = priceAmountMicros;
}
public String getPriceCurrencyCode() {
return priceCurrencyCode;
}
public void setPriceCurrencyCode(String priceCurrencyCode) {
this.priceCurrencyCode = priceCurrencyCode;
}
public String getSubscriptionPeriod() {
return subscriptionPeriod;
}
public void setSubscriptionPeriod(String subscriptionPeriod) {
this.subscriptionPeriod = subscriptionPeriod;
}
public String getFreeTrialPeriod() {
return freeTrialPeriod;
}
public void setFreeTrialPeriod(String freeTrialPeriod) {
this.freeTrialPeriod = freeTrialPeriod;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
From Result activity:
public class Result implements Serializable{
#SerializedName("SkuDetails")
#Expose
private ArrayList<Details> details = new ArrayList<Details>();
/**
*
* #return The SkuDetails
*/
public ArrayList<Details> getDetails() {
return details;
}
/**
*
* #param details
* The details
*/
public void setDetails(ArrayList<Details> details) {
this.details = details;
}
}*
Oh..and the response I was trying to parse (skuDetailsList.toString()) is:
[
SkuDetails: {
"productId": "basic_sub",
"type": "subs",
"price": "$0.99",
"price_amount_micros": 990000,
"price_currency_code": "USD",
"subscriptionPeriod": "P1M",
"freeTrialPeriod": "P4W2D",
"title": "Basic Subscription Service (DadBod Recipes)",
"description": "Basic Subscription Service for DadBodRecipes"
},
SkuDetails: {
"productId": "enterprise_sub",
"type": "subs",
"price": "$2.99",
"price_amount_micros": 2990000,
"price_currency_code": "USD",
"subscriptionPeriod": "P1M",
"freeTrialPeriod": "P4W2D",
"title": "Enterprise Subscription Service (DadBod Recipes)",
"description": "Enterprise Subscription Service for DadBodRecipes"
}
]
Issue is because, the result you're getting is as <Key-Value> pair (not as JSON object/Array, but similar to it).
So you'll need to make it to JSONObject first and then parse it using Gson like below:
Map<String, String> params = skuDetailsList;
JSONObject object = new JSONObject(params);
Result result = gson.fromJson(object.toString(), Result.class);
Do like this, hope it helps !
You are trying to parse your json
[
as
{
when you see the [ it represents a list
when you see the { it represents an object.
I'm pretty sure you know that as you built a wrapper class, but your wrapper class is also an object, not an array.
So your choices are to have your wrapper class extend ArrayList or some form of List.
Or
Tell your Json converter that the base is an Array and you want the first object in the list is an object of your type.
I have in a rest response this json:
{
"TRANS": {
"HPAY": [
{
"ID": "1234",
"DATE": "10/09/2011 18:09:27",
"REC": "wallet Ricaricato",
"COM": "Tasso Commissione",
"MSG": "Commento White Brand",
"STATUS": "3",
"EXTRA": {
"IS3DS": "0",
"CTRY": "FRA",
"AUTH": "455622"
},
"INT_MSG": "05-00-05 ERR_PSP_REFUSED",
"MLABEL": "IBAN",
"TYPE": "1"
}
]
}
}
I have made pojo class to map this json in java.
public class Trans {
private List<Hpay> hpay;
public Trans(){
}
//getter and setter
}
public class Hpay {
private String id;
private String date;
private String com;
private String msg;
private String status;
private List<Extra> extra;
private String int_msg;
private String mlabel;
private String type;
public Hpay(){
}
//getter and setter
}
I try to map the object with Gson library.
Gson gson=new Gson();
Trans transaction=gson.fromJson(response.toString(), Trans.class);
If i call hpay method on transaction i have null..i don't know why...
I have deleted previous answer and add new one as par your requirement
JSON String :
{
"TRANS": {
"HPAY": [{
"ID": "1234",
"DATE": "10/09/2011 18:09:27",
"REC": "wallet Ricaricato",
"COM": "Tasso Commissione",
"MSG": "Commento White Brand",
"STATUS": "3",
"EXTRA": {
"IS3DS": "0",
"CTRY": "FRA",
"AUTH": "455622"
},
"INT_MSG": "05-00-05 ERR_PSP_REFUSED",
"MLABEL": "IBAN",
"TYPE": "1"
}
]
}
}
Java Objects : (Here Extra is not list)
public class MyObject {
#SerializedName("TRANS")
#Expose
private Trans trans;
public Trans getTRANS() {return trans;}
public void setTRANS(Trans trans) {this.trans = trans;}
}
public class Trans {
#SerializedName("HPAY")
#Expose
private List<HPay> hPay;
public List<HPay> getHPAY() {return hPay;}
public void setHPAY(List<HPay> hPay) {this.hPay = hPay;}
}
public class HPay {
#SerializedName("ID")
#Expose
private String id;
#SerializedName("DATE")
#Expose
private String date;
#SerializedName("REC")
#Expose
private String rec;
#SerializedName("COM")
#Expose
private String com;
#SerializedName("MSG")
#Expose
private String msg;
#SerializedName("STATUS")
#Expose
private String status;
#SerializedName("EXTRA")
#Expose
private Extra extra;
#SerializedName("INT_MSG")
#Expose
private String intMsg;
#SerializedName("MLABEL")
#Expose
private String mLabel;
#SerializedName("TYPE")
#Expose
private String type;
public String getID() {return id;}
public void setID(String id) {this.id = id;}
public String getDATE() {return date;}
public void setDATE(String date) {this.date = date;}
public String getREC() {return rec;}
public void setREC(String rec) {this.rec = rec;}
public String getCOM() {return com;}
public void setCOM(String com) {this.com = com;}
public String getMSG() {return msg;}
public void setMSG(String msg) {this.msg = msg;}
public String getSTATUS() {return status;}
public void setSTATUS(String status) {this.status = status;}
public Extra getEXTRA() {return extra;}
public void setEXTRA(Extra extra) {this.extra = extra;}
public String getINTMSG() {return intMsg;}
public void setINTMSG(String intMsg) {this.intMsg = intMsg;}
public String getMLABEL() {return mLabel;}
public void setMLABEL(String mLabel) {this.mLabel = mLabel;}
public String getTYPE() {return type;}
public void setTYPE(String type) {this.type = type;}
}
public class Extra {
#SerializedName("IS3DS")
#Expose
private String is3ds;
#SerializedName("CTRY")
#Expose
private String ctry;
#SerializedName("AUTH")
#Expose
private String auth;
public String getIS3DS() { return is3ds; }
public void setIS3DS(String is3ds) { this.is3ds = is3ds; }
public String getCTRY() { return ctry; }
public void setCTRY(String ctry) { this.ctry = ctry; }
public String getAUTH() { return auth; }
public void setAUTH(String auth) { this.auth = auth; }
}
Conversion Logic :
import com.google.gson.Gson;
public class NewClass {
public static void main(String[] args) {
Gson g = new Gson();
g.fromJson(json, MyObject.class);
}
static String json = "{ \"TRANS\": { \"HPAY\": [{ \"ID\": \"1234\", \"DATE\": \"10/09/2011 18:09:27\", \"REC\": \"wallet Ricaricato\", \"COM\": \"Tasso Commissione\", \"MSG\": \"Commento White Brand\", \"STATUS\": \"3\", \"EXTRA\": { \"IS3DS\": \"0\", \"CTRY\": \"FRA\", \"AUTH\": \"455622\" }, \"INT_MSG\": \"05-00-05 ERR_PSP_REFUSED\", \"MLABEL\": \"IBAN\", \"TYPE\": \"1\" } ] } }";
}
Here I use Google Gosn lib for conversion.
And need to import bellow classes for annotation
com.google.gson.annotations.Expose;
com.google.gson.annotations.SerializedName;
First parse the json data using json.simple and then set the values using setters
Object obj = parser.parse(new FileReader( "file.json" ));
JSONObject jsonObject = (JSONObject) obj;
JSONArray hpayObj= (JSONArray) jsonObject.get("HPAY");
//get the first element of array
JSONObject details= hpayObj.getJSONArray(0);
String id = (String)details.get("ID");
//set the value of the id field in the setter of class Trans
new Trans().setId(id);
new Trans().setDate((String)details.get("DATE"));
new Trans().setRec((String)details.get("REC"));
and so on..
//get the second array element
JSONObject intMsgObj= hpayObj.getJSONArray(1);
new Trans().setIntmsg((String)details.get("INT_MSG"));
//get the third array element
JSONObject mlabelObj= hpayObj.getJSONArray(2);
new Trans().setMlabel((String)details.get("MLABEL"));
JSONObject typeObj= hpayObj.getJSONArray(3);
new Trans().setType((String)details.get("TYPE"));
Now you can get the values using your getter methods.
I'm trying to parse a JSON object, part of which looks like this :
{
"status":{
"rcode":200,
"message":"OK"
},
"data":{
"0":{
"SubFranchiseID":"0",
"OutletID":"607",
"OutletName":"Spill ",
"BrandID":"403",
"Address":"J-349, JP Road, Opp. Apna Bazar, JP Rd, D.N.Nagar, Andheri West, Mumbai, Maharashtra, India",
"NeighbourhoodID":"1",
"CityID":"1",
"Email":null,
"Timings":"Everyday: 6 pm to 1:30 am.",
"CityRank":null,
"Latitude":"19.127473",
"Longitude":"72.832545",
"Pincode":null,
"Landmark":null,
"Streetname":null,
"BrandName":"Spill ",
"OutletURL":"https:\/\/plus.google.com\/111539701326240643109\/about?hl=en-US",
"NumCoupons":1,
"NeighbourhoodName":"Andheri West",
"PhoneNumber":"+91 22 2642 5895",
"CityName":"Mumbai",
"Distance":8205.2235,
"Categories":[
{
"OfflineCategoryID":"32",
"Name":"Continental",
"ParentCategoryID":"1",
"CategoryType":"Cuisine"
},
{
"OfflineCategoryID":"13",
"Name":"Bar and Restaurant",
"ParentCategoryID":"1",
"CategoryType":"TypeOfRestaurant"
},
{
"OfflineCategoryID":"17",
"Name":"Italian",
"ParentCategoryID":"1",
"CategoryType":"Cuisine"
},
{
"OfflineCategoryID":"1",
"Name":"Restaurant",
"ParentCategoryID":null,
"CategoryType":""
},
{
"OfflineCategoryID":"21",
"Name":"North Indian",
"ParentCategoryID":"1",
"CategoryType":"Cuisine"
}
],
"LogoURL":"http:\/\/www.google.in\/sitespecific\/media\/generated\/offlineimages\/logo_403.jpg",
"CoverURL":"http:\/\/www.google.in\/sitespecific\/media\/generated\/offlineimages\/cover_607.jpg"
},
"1 "{
"SubFranchiseID":"1",
"OutletID":"60",
"OutletName":"Bill ",
.
.
.
}
}
There are nearly 35 Json objects and nested JsonArrays for each of these objects.I'm trying to get data like this :
url = new URL(uri);
URLConnection connection = url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
reader.close();
json =sb.toString();
JSONObject sjson=json.getJSONObject("data");
Log.d("sjson values-->",sjson+"--");
**JSONObject ssjson=sjson.getJSONObject("0");**
And now i am getting each of values like this :
String outletName = ssjson.getString("OutletName");
My question is there any better way (loop) through all objects ( 0,1,...35) and get data for each individual object separately.
Example json
{
"status": {
"rcode": "200",
"message": "Good, you got me!!!"
},
"data": [
{
"SubFranchiseID": "0",
"OutletID": "607",
"OutletName": "Spill",
},
{
"SubFranchiseID": "0",
"OutletID": "607",
"OutletName": "Spill"
}
]
}
Represent the json in terms of plain java classes with getter and
setters
First create a the root class (for the root object)
public class Root {
//For the status object
private Status status;
//For the array of data objects
private List<Data> data;
//create setters and getters for the two properties.
}
public class Status {
private String rcode;
//this maps to the rcode in the status object in json
private String message;
//create setters and getters for the two
}
public class Data {
private String SubFranchiseID;
private String OutletID;
private String OutletName;
//create setters and getters for these properties.
}
Now, lets do the magic with gson (The serialization of the json in to the ready made classes)
reader.close();
json =sb.toString();
Root root = new Gson().fromJson(response, Root.class);
//get the rcode
if(root.getStatus().getrCode().equalsIgnoreCase("200"))
{
//print the data.
for(Data d : root.getData()) {
System.out.println(d.getSubFranchiseID()+"-"+d.getOutletID()+"-"+d.getOutletName());
}
}
A small note for using gson.
1.) The property names inside the classes should match the property in the json or else use a `#SerializeName("propertyname")`.
2.) An array of objects would map to List<YourObject> , for eg : the data property in the json.
3.) You can have default value for your properties without creating getters and setters for them like
private boolean isJson = true;
Thanks for the help. I have a lot of json objects inside "data" -> "0" like "Outletname","OutletID ",etc , before Json Array ( "Categories" ). i have created a model class for my data. Now i want to itterate json objects data using Gson.Part of my json data
"0":{
"SubFranchiseID":"0",
"OutletID":"607",
"OutletName":"Spill ",
"BrandID":"403",
"Address":"J-349, JP Road, Opp. Apna Bazar, JP Rd, D.N.Nagar, Andheri West, Mumbai, Maharashtra, India",
"NeighbourhoodID":"1",
"CityID":"1",
"Email":null,
"Timings":"Everyday: 6 pm to 1:30 am.",
"CityRank":null,
"Latitude":"19.127473",
"Longitude":"72.832545",
"Pincode":null,
"Landmark":null,
"Streetname":null,
"BrandName":"Spill ",
"OutletURL":"https:\/\/plus.google.com\/111539701326240643109\/about?hl=en-US",
"NumCoupons":1,
"NeighbourhoodName":"Andheri West",
"PhoneNumber":"+91 22 2642 5895",
"CityName":"Mumbai",
"Distance":8205.2235,
"Categories":[
{
"OfflineCategoryID":"32",
"Name":"Continental",
"ParentCategoryID":"1",
"CategoryType":"Cuisine"
},
{
"OfflineCategoryID":"13",
"Name":"Bar and Restaurant",
"ParentCategoryID":"1",
"CategoryType":"TypeOfRestaurant"
},
{
"OfflineCategoryID":"17",
"Name":"Italian",
"ParentCategoryID":"1",
"CategoryType":"Cuisine"
},
{
"OfflineCategoryID":"1",
"Name":"Restaurant",
"ParentCategoryID":null,
"CategoryType":""
},
{
"OfflineCategoryID":"21",
"Name":"North Indian",
"ParentCategoryID":"1",
"CategoryType":"Cuisine"
}
],
"LogoURL":"http:\/\/www.google.in\/sitespecific\/media\/generated\/offlineimages\/logo_403.jpg",
"CoverURL":"http:\/\/www.google.in\/sitespecific\/media\/generated\/offlineimages\/cover_607.jpg"
},
}
My java Model Class :
/**
* SubFranchiseID : 0
* OutletID : 607
* OutletName : Spill
* BrandID : 403
* Address : J-349, JP Road, Opp. Apna Bazar, JP Rd, D.N.Nagar, Andheri West, Mumbai, Maharashtra, India
* NeighbourhoodID : 1
* CityID : 1
* Email : null
* Timings : Everyday: 6 pm to 1:30 am.
* CityRank : null
* Latitude : 19.127473
* Longitude : 72.832545
* Pincode : null
* Landmark : null
* Streetname : null
* BrandName : Spill
* OutletURL : https://plus.google.com/111539701326240643109/about?hl=en-US
* NumCoupons : 1
* NeighbourhoodName : Andheri West
* PhoneNumber : +91 22 2642 5895
* CityName : Mumbai
* Distance : 8205.2235
* Categories : [{"OfflineCategoryID":"32","Name":"Continental","ParentCategoryID":"1","CategoryType":"Cuisine"},{"OfflineCategoryID":"13","Name":"Bar and Restaurant","ParentCategoryID":"1","CategoryType":"TypeOfRestaurant"},{"OfflineCategoryID":"17","Name":"Italian","ParentCategoryID":"1","CategoryType":"Cuisine"},{"OfflineCategoryID":"1","Name":"Restaurant","ParentCategoryID":null,"CategoryType":""},{"OfflineCategoryID":"21","Name":"North Indian","ParentCategoryID":"1","CategoryType":"Cuisine"}]
* LogoURL : http://www.google.in/sitespecific/media/generated/offlineimages/logo_403.jpg
* CoverURL : http://www.google.in/sitespecific/media/generated/offlineimages/cover_607.jpg
*/
public static class OutletDetailsEntity {
private String SubFranchiseID;
private String OutletID;
private String OutletName;
private String BrandID;
private String Address;
private String NeighbourhoodID;
private String CityID;
private Object Email;
private String Timings;
private Object CityRank;
private String Latitude;
private String Longitude;
private Object Pincode;
private Object Landmark;
private Object Streetname;
private String BrandName;
private String OutletURL;
private int NumCoupons;
private String NeighbourhoodName;
private String PhoneNumber;
private String CityName;
private double Distance;
private String LogoURL;
private String CoverURL;
private List<CategoriesEntity> Categories;
public void setSubFranchiseID(String SubFranchiseID) {
this.SubFranchiseID = SubFranchiseID;
}
public void setOutletID(String OutletID) {
this.OutletID = OutletID;
}
public void setOutletName(String OutletName) {
this.OutletName = OutletName;
}
public void setBrandID(String BrandID) {
this.BrandID = BrandID;
}
public void setAddress(String Address) {
this.Address = Address;
}
public void setNeighbourhoodID(String NeighbourhoodID) {
this.NeighbourhoodID = NeighbourhoodID;
}
public void setCityID(String CityID) {
this.CityID = CityID;
}
public void setEmail(Object Email) {
this.Email = Email;
}
public void setTimings(String Timings) {
this.Timings = Timings;
}
public void setCityRank(Object CityRank) {
this.CityRank = CityRank;
}
public void setLatitude(String Latitude) {
this.Latitude = Latitude;
}
public void setLongitude(String Longitude) {
this.Longitude = Longitude;
}
public void setPincode(Object Pincode) {
this.Pincode = Pincode;
}
public void setLandmark(Object Landmark) {
this.Landmark = Landmark;
}
public void setStreetname(Object Streetname) {
this.Streetname = Streetname;
}
public void setBrandName(String BrandName) {
this.BrandName = BrandName;
}
public void setOutletURL(String OutletURL) {
this.OutletURL = OutletURL;
}
public void setNumCoupons(int NumCoupons) {
this.NumCoupons = NumCoupons;
}
public void setNeighbourhoodName(String NeighbourhoodName) {
this.NeighbourhoodName = NeighbourhoodName;
}
public void setPhoneNumber(String PhoneNumber) {
this.PhoneNumber = PhoneNumber;
}
public void setCityName(String CityName) {
this.CityName = CityName;
}
public void setDistance(double Distance) {
this.Distance = Distance;
}
public void setLogoURL(String LogoURL) {
this.LogoURL = LogoURL;
}
public void setCoverURL(String CoverURL) {
this.CoverURL = CoverURL;
}
public void setCategories(List<CategoriesEntity> Categories) {
this.Categories = Categories;
}
public String getSubFranchiseID() {
return SubFranchiseID;
}
public String getOutletID() {
return OutletID;
}
public String getOutletName() {
return OutletName;
}
public String getBrandID() {
return BrandID;
}
public String getAddress() {
return Address;
}
public String getNeighbourhoodID() {
return NeighbourhoodID;
}
public String getCityID() {
return CityID;
}
public Object getEmail() {
return Email;
}
public String getTimings() {
return Timings;
}
public Object getCityRank() {
return CityRank;
}
public String getLatitude() {
return Latitude;
}
public String getLongitude() {
return Longitude;
}
public Object getPincode() {
return Pincode;
}
public Object getLandmark() {
return Landmark;
}
public Object getStreetname() {
return Streetname;
}
public String getBrandName() {
return BrandName;
}
public String getOutletURL() {
return OutletURL;
}
public int getNumCoupons() {
return NumCoupons;
}
public String getNeighbourhoodName() {
return NeighbourhoodName;
}
public String getPhoneNumber() {
return PhoneNumber;
}
public String getCityName() {
return CityName;
}
public double getDistance() {
return Distance;
}
public String getLogoURL() {
return LogoURL;
}
public String getCoverURL() {
return CoverURL;
}
I have been following other answers but there is a missing step that i cant find which is resulting in call being successful but the data not being parsed correctly because the first call i make returns a list of objects but only 1 object is returned which is all null
MyModel.java
public class MyModel {
#SerializedName("url")
private String mUrl;
#SerializedName("name")
private String mName;
#SerializedName("description")
private String mDescription;
}
MyModelDeserializer.java
This just checks if its array or object and will simply return the array
public class MyModelTypeAdapter implements JsonDeserializer<ArrayList<MyModel>>{
#Override
public ArrayList<MyModel> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
ArrayList<MyModel> objects = new ArrayList<>();
if(json.isJsonArray()){
for(JsonElement e : json.getAsJsonArray()){
objects.add((MyModel)context.deserialize(e,MyModel.class));
}
}else if(json.isJsonObject()){
objects.add((MyModel)context.deserialize(json,MyModel.class));
}
return objects;
}
}
Some other stuff
Gson gson = new GsonBuilder()
.registerTypeAdapter(new TypeToken<ArrayList<MyModel>>() {}.getType(), new MyModelTypeAdapter())
.create();
restAdapter = new RestAdapter.Builder()
.setEndpoint(BuildConstants.BASE_URL)
.setConverter(new GsonConverter(gson))
.setClient(new OkClient(okHttpClient))
.setLogLevel(RestAdapter.LogLevel.FULL)
.build();
This is the part which confusing me, what do i put as the return type of the callback
#GET(URLConstants.LIST_URL)
void getData(Callback<ArrayList<MyModel>> callback);
Edit JSON data
{
"places": [
{
"url": "www.google.com",
"name": "Google",
"description": "Search engine"
},
{
"url": "www.Facebook.com",
"name": "Facebook",
"description": "Social Network"
},
{
"url": "www.amazon.com",
"name": "Amazon",
"description": "Shopping"
}
]
}
First create a POJO class to handle json. You can use jsonschema2pojo to create pojo class for your json:
public class MyModel {
#Expose
private List<Place> places = new ArrayList<Place>();
/**
*
* #return
* The places
*/
public List<Place> getPlaces() {
return places;
}
/**
*
* #param places
* The places
*/
public void setPlaces(List<Place> places) {
this.places = places;
}
}
public class Place {
#Expose
private String url;
#Expose
private String name;
#Expose
private String description;
/**
*
* #return
* The url
*/
public String getUrl() {
return url;
}
/**
*
* #param url
* The url
*/
public void setUrl(String url) {
this.url = url;
}
/**
*
* #return
* The name
*/
public String getName() {
return name;
}
/**
*
* #param name
* The name
*/
public void setName(String name) {
this.name = name;
}
/**
*
* #return
* The description
*/
public String getDescription() {
return description;
}
/**
*
* #param description
* The description
*/
public void setDescription(String description) {
this.description = description;
}
}
Next create a restadapter like this:
public class SimpleRestClient {
private SimpleRestApi simpleRestApi;
public SimpleRestClient() {
RestAdapter restAdapter = new RestAdapter.Builder()
.setLogLevel(RestAdapter.LogLevel.FULL)
.setEndpoint(Constants.BASE_URL)
.build();
simpleRestApi = restAdapter.create(SimpleRestApi.class);
}
public SimpleRestApi getSimpleRestApi() {
return simpleRestApi;
}
}
Now to create the api interface. Here we are setting our POJO class to handle the json response:
public interface SimpleRestApi {
#GET("Enter URL")
public void getSimpleResponse(Callback<MyModel> handlerCallback);
}
Finally call it as follows:
simpleRestApi = new SimpleRestClient().getSimpleRestApi();
simpleRestApi.getSimpleResponse(new Callback<MyModel>() {
#Override
public void success(MyModel responseHandler, Response response) {
// here you can get your url, name and description.
}
#Override
public void failure(RetrofitError error) {
progress.dismiss();
Log.e("CLASS", "JSON: " + error.getCause());
}
});
References:
jsonschema2pojo
A smart way to use retrofit