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()
}
I am getting this error message in my logcat 03-18 12:06:36.972: W/System.err(24574): org.json.JSONException: No value for title an I am stuck here. I am using Gson to parse JSON data. Here is my MainActivity and Model class.
I looked into other questions posted for same JSON Exception but I couldn't find the solution so I posted this question for my project
Also please advise if I am using correct method to display the data in the textview.
MainActivity
public class MainActivity extends AppCompatActivity {
public static final String Logcat = "vmech";
Button searchButton;
EditText editTextSearch;
TextView textViewDisplayResult;
String newText;
String urlstring;
public static final String MyAPIKey = "Your_Api_Key";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
searchButton = (Button) findViewById(R.id.buttonSerch);
editTextSearch = (EditText) findViewById(R.id.editTextSearch);
textViewDisplayResult = (TextView) findViewById(R.id.textViewDisplayResult);
searchButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
newText = editTextSearch.getText().toString();
if(newText.length()>0){
newText = newText.replace(" ", "+");
urlstring = "https://www.googleapis.com/books/v1/volumes?q=";
urlstring = urlstring + newText + "&maxResults=5" + "&key=" + MyAPIKey;
}
else {
Toast.makeText(MainActivity.this, "Please enter a book name to search.", Toast.LENGTH_LONG).show();
}
new JSONTask().execute(urlstring);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
Toast.makeText(this, "This is the Settings item", Toast.LENGTH_LONG).show();
return true;
}
public class JSONTask extends AsyncTask<String, String, List<BookInfoModel>>{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected List<BookInfoModel> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader bufferedReader = null;
try {
URL url = new URL(urlstring);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream inputstream = connection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputstream));
StringBuffer stringbuffer = new StringBuffer();
String line = "";
while ((line = bufferedReader.readLine()) != null) {
stringbuffer.append(line);
}
String finalJson = stringbuffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("items");
List<BookInfoModel> bookInfoModelList = new ArrayList<>();
String idText = null;
Gson gson = new Gson();
for(int i=0; i<parentArray.length(); i++){
JSONObject finalObject = parentArray.getJSONObject(i);
BookInfoModel bookInfoModel = gson.fromJson(finalObject.toString(),BookInfoModel.class);
bookInfoModelList.add(bookInfoModel);
}
return bookInfoModelList;
} catch (IOException e){
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null)
{
connection.disconnect();
}
try {
if (bufferedReader != null){
bufferedReader.close();
}
}catch (IOException e){
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<BookInfoModel> result) {
super.onPostExecute(result);
textViewDisplayResult.setText((CharSequence) result);
}
}
}
Here is my model class for JSON data.
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class BookInfoModel {
private List<Items> items;
private String totalItems;
private String kind;
public List<Items> getItems() {
return items;
}
public void setItems(List<Items> items) {
this.items = items;
}
public String getTotalItems ()
{
return totalItems;
}
public void setTotalItems (String totalItems)
{
this.totalItems = totalItems;
}
public String getKind ()
{
return kind;
}
public void setKind (String kind)
{
this.kind = kind;
}
public class Items
{
private SaleInfo saleInfo;
private String id;
private SearchInfo searchInfo;
private String etag;
private List<VolumeInfo> volumeInfo;
private String selfLink;
private AccessInfo accessInfo;
private String kind;
public SaleInfo getSaleInfo ()
{
return saleInfo;
}
public void setSaleInfo (SaleInfo saleInfo)
{
this.saleInfo = saleInfo;
}
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
public SearchInfo getSearchInfo ()
{
return searchInfo;
}
public void setSearchInfo (SearchInfo searchInfo)
{
this.searchInfo = searchInfo;
}
public String getEtag ()
{
return etag;
}
public void setEtag (String etag)
{
this.etag = etag;
}
public List<VolumeInfo> getVolumeInfo() {
return volumeInfo;
}
public void setVolumeInfo(List<VolumeInfo> volumeInfo) {
this.volumeInfo = volumeInfo;
}
public String getSelfLink ()
{
return selfLink;
}
public void setSelfLink (String selfLink)
{
this.selfLink = selfLink;
}
public AccessInfo getAccessInfo ()
{
return accessInfo;
}
public void setAccessInfo (AccessInfo accessInfo)
{
this.accessInfo = accessInfo;
}
public String getKind ()
{
return kind;
}
public void setKind (String kind)
{
this.kind = kind;
}
public class SearchInfo
{
private String textSnippet;
public String getTextSnippet ()
{
return textSnippet;
}
public void setTextSnippet (String textSnippet)
{
this.textSnippet = textSnippet;
}
}
public class AccessInfo
{
private String webReaderLink;
private String textToSpeechPermission;
private String publicDomain;
private String viewability;
private String accessViewStatus;
private Pdf pdf;
private Epub epub;
private String embeddable;
private String quoteSharingAllowed;
private String country;
public String getWebReaderLink ()
{
return webReaderLink;
}
public void setWebReaderLink (String webReaderLink)
{
this.webReaderLink = webReaderLink;
}
public String getTextToSpeechPermission ()
{
return textToSpeechPermission;
}
public void setTextToSpeechPermission (String textToSpeechPermission)
{
this.textToSpeechPermission = textToSpeechPermission;
}
public String getPublicDomain ()
{
return publicDomain;
}
public void setPublicDomain (String publicDomain)
{
this.publicDomain = publicDomain;
}
public String getViewability ()
{
return viewability;
}
public void setViewability (String viewability)
{
this.viewability = viewability;
}
public String getAccessViewStatus ()
{
return accessViewStatus;
}
public void setAccessViewStatus (String accessViewStatus)
{
this.accessViewStatus = accessViewStatus;
}
public Pdf getPdf ()
{
return pdf;
}
public void setPdf (Pdf pdf)
{
this.pdf = pdf;
}
public Epub getEpub ()
{
return epub;
}
public void setEpub (Epub epub)
{
this.epub = epub;
}
public String getEmbeddable ()
{
return embeddable;
}
public void setEmbeddable (String embeddable)
{
this.embeddable = embeddable;
}
public String getQuoteSharingAllowed ()
{
return quoteSharingAllowed;
}
public void setQuoteSharingAllowed (String quoteSharingAllowed)
{
this.quoteSharingAllowed = quoteSharingAllowed;
}
public String getCountry ()
{
return country;
}
public void setCountry (String country)
{
this.country = country;
}
public class Pdf
{
private String acsTokenLink;
private String isAvailable;
public String getAcsTokenLink ()
{
return acsTokenLink;
}
public void setAcsTokenLink (String acsTokenLink)
{
this.acsTokenLink = acsTokenLink;
}
public String getIsAvailable ()
{
return isAvailable;
}
public void setIsAvailable (String isAvailable)
{
this.isAvailable = isAvailable;
}
}
public class Epub
{
private String acsTokenLink;
private String isAvailable;
public String getAcsTokenLink ()
{
return acsTokenLink;
}
public void setAcsTokenLink (String acsTokenLink)
{
this.acsTokenLink = acsTokenLink;
}
public String getIsAvailable ()
{
return isAvailable;
}
public void setIsAvailable (String isAvailable)
{
this.isAvailable = isAvailable;
}
}
}
public class SaleInfo
{
private RetailPrice retailPrice;
private String saleability;
private ListPrice listPrice;
private Offers[] offers;
private String buyLink;
private String isEbook;
private String country;
public RetailPrice getRetailPrice ()
{
return retailPrice;
}
public void setRetailPrice (RetailPrice retailPrice)
{
this.retailPrice = retailPrice;
}
public String getSaleability ()
{
return saleability;
}
public void setSaleability (String saleability)
{
this.saleability = saleability;
}
public ListPrice getListPrice ()
{
return listPrice;
}
public void setListPrice (ListPrice listPrice)
{
this.listPrice = listPrice;
}
public Offers[] getOffers ()
{
return offers;
}
public void setOffers (Offers[] offers)
{
this.offers = offers;
}
public String getBuyLink ()
{
return buyLink;
}
public void setBuyLink (String buyLink)
{
this.buyLink = buyLink;
}
public String getIsEbook ()
{
return isEbook;
}
public void setIsEbook (String isEbook)
{
this.isEbook = isEbook;
}
public String getCountry ()
{
return country;
}
public void setCountry (String country)
{
this.country = country;
}
public class Offers
{
private RetailPrice retailPrice;
private ListPrice listPrice;
private String finskyOfferType;
public RetailPrice getRetailPrice ()
{
return retailPrice;
}
public void setRetailPrice (RetailPrice retailPrice)
{
this.retailPrice = retailPrice;
}
public ListPrice getListPrice ()
{
return listPrice;
}
public void setListPrice (ListPrice listPrice)
{
this.listPrice = listPrice;
}
public String getFinskyOfferType ()
{
return finskyOfferType;
}
public void setFinskyOfferType (String finskyOfferType)
{
this.finskyOfferType = finskyOfferType;
}
}
public class RetailPrice
{
private String amount;
private String currencyCode;
public String getAmount ()
{
return amount;
}
public void setAmount (String amount)
{
this.amount = amount;
}
public String getCurrencyCode ()
{
return currencyCode;
}
public void setCurrencyCode (String currencyCode)
{
this.currencyCode = currencyCode;
}
}
public class ListPrice
{
private String amount;
private String currencyCode;
public String getAmount ()
{
return amount;
}
public void setAmount (String amount)
{
this.amount = amount;
}
public String getCurrencyCode ()
{
return currencyCode;
}
public void setCurrencyCode (String currencyCode)
{
this.currencyCode = currencyCode;
}
}
}
public class VolumeInfo
{
private String pageCount;
private String averageRating;
private ReadingModes readingModes;
private String infoLink;
private String printType;
private String allowAnonLogging;
private String publisher;
private String[] authors;
private String canonicalVolumeLink;
#SerializedName("title")
private String title;
private String previewLink;
private String description;
private String ratingsCount;
private ImageLinks imageLinks;
private String contentVersion;
private String[] categories;
private String language;
private String publishedDate;
private IndustryIdentifiers[] industryIdentifiers;
private String maturityRating;
public String getPageCount ()
{
return pageCount;
}
public void setPageCount (String pageCount)
{
this.pageCount = pageCount;
}
public String getAverageRating ()
{
return averageRating;
}
public void setAverageRating (String averageRating)
{
this.averageRating = averageRating;
}
public ReadingModes getReadingModes ()
{
return readingModes;
}
public void setReadingModes (ReadingModes readingModes)
{
this.readingModes = readingModes;
}
public String getInfoLink ()
{
return infoLink;
}
public void setInfoLink (String infoLink)
{
this.infoLink = infoLink;
}
public String getPrintType ()
{
return printType;
}
public void setPrintType (String printType)
{
this.printType = printType;
}
public String getAllowAnonLogging ()
{
return allowAnonLogging;
}
public void setAllowAnonLogging (String allowAnonLogging)
{
this.allowAnonLogging = allowAnonLogging;
}
public String getPublisher ()
{
return publisher;
}
public void setPublisher (String publisher)
{
this.publisher = publisher;
}
public String[] getAuthors ()
{
return authors;
}
public void setAuthors (String[] authors)
{
this.authors = authors;
}
public String getCanonicalVolumeLink ()
{
return canonicalVolumeLink;
}
public void setCanonicalVolumeLink (String canonicalVolumeLink)
{
this.canonicalVolumeLink = canonicalVolumeLink;
}
public String getTitle ()
{
return title;
}
public void setTitle (String title)
{
this.title = title;
}
public String getPreviewLink ()
{
return previewLink;
}
public void setPreviewLink (String previewLink)
{
this.previewLink = previewLink;
}
public String getDescription ()
{
return description;
}
public void setDescription (String description)
{
this.description = description;
}
public String getRatingsCount ()
{
return ratingsCount;
}
public void setRatingsCount (String ratingsCount)
{
this.ratingsCount = ratingsCount;
}
public ImageLinks getImageLinks ()
{
return imageLinks;
}
public void setImageLinks (ImageLinks imageLinks)
{
this.imageLinks = imageLinks;
}
public String getContentVersion ()
{
return contentVersion;
}
public void setContentVersion (String contentVersion)
{
this.contentVersion = contentVersion;
}
public String[] getCategories ()
{
return categories;
}
public void setCategories (String[] categories)
{
this.categories = categories;
}
public String getLanguage ()
{
return language;
}
public void setLanguage (String language)
{
this.language = language;
}
public String getPublishedDate ()
{
return publishedDate;
}
public void setPublishedDate (String publishedDate)
{
this.publishedDate = publishedDate;
}
public IndustryIdentifiers[] getIndustryIdentifiers ()
{
return industryIdentifiers;
}
public void setIndustryIdentifiers (IndustryIdentifiers[] industryIdentifiers)
{
this.industryIdentifiers = industryIdentifiers;
}
public String getMaturityRating ()
{
return maturityRating;
}
public void setMaturityRating (String maturityRating)
{
this.maturityRating = maturityRating;
}
public class ImageLinks
{
private String thumbnail;
private String smallThumbnail;
public String getThumbnail ()
{
return thumbnail;
}
public void setThumbnail (String thumbnail)
{
this.thumbnail = thumbnail;
}
public String getSmallThumbnail ()
{
return smallThumbnail;
}
public void setSmallThumbnail (String smallThumbnail)
{
this.smallThumbnail = smallThumbnail;
}
}
public class ReadingModes
{
private String text;
private String image;
public String getText ()
{
return text;
}
public void setText (String text)
{
this.text = text;
}
public String getImage ()
{
return image;
}
public void setImage (String image)
{
this.image = image;
}
}
public class IndustryIdentifiers
{
private String type;
private String identifier;
public String getType ()
{
return type;
}
public void setType (String type)
{
this.type = type;
}
public String getIdentifier ()
{
return identifier;
}
public void setIdentifier (String identifier)
{
this.identifier = identifier;
}
}
}
}
}
Here is the JSON data I m trying to Parse.
{
"kind": "books#volumes",
"totalItems": 1557,
"items": [
{
"kind": "books#volume",
"id": "An4_e3Cr3zAC",
"etag": "DWmqBRkB8dw",
"selfLink": "https://www.googleapis.com/books/v1/volumes/An4_e3Cr3zAC",
"volumeInfo": {
"title": "The Rules of the Game",
"authors": [
"Neil Strauss"
],
"publisher": "Canongate Books",
"publishedDate": "2011-09-29",
"description": "If you want to play The Game you need to know The Rules This book is not a story.",
"industryIdentifiers": [
{
"type": "ISBN_13",
"identifier": "9781847673558"
},
{
"type": "ISBN_10",
"identifier": "1847673554"
}
],
"readingModes": {
"text": true,
"image": true
},
"pageCount": 352,
"printType": "BOOK",
"categories": [
"Biography & Autobiography"
],
"averageRating": 3.5,
"ratingsCount": 82,
"maturityRating": "NOT_MATURE",
"allowAnonLogging": true,
"contentVersion": "1.7.6.0.preview.3",
"imageLinks": {
"smallThumbnail": "http://books.google.co.in/books/content?id=An4_e3Cr3zAC&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api",
"thumbnail": "http://books.google.co.in/books/content?id=An4_e3Cr3zAC&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api"
},
"language": "en",
"previewLink": "http://books.google.co.in/books?id=An4_e3Cr3zAC&printsec=frontcover&dq=game&hl=&cd=1&source=gbs_api",
"infoLink": "http://books.google.co.in/books?id=An4_e3Cr3zAC&dq=game&hl=&source=gbs_api",
"canonicalVolumeLink": "http://books.google.co.in/books/about/The_Rules_of_the_Game.html?hl=&id=An4_e3Cr3zAC"
},
"saleInfo": {
"country": "IN",
"saleability": "FOR_SALE",
"isEbook": true,
"listPrice": {
"amount": 399.0,
"currencyCode": "INR"
},
"retailPrice": {
"amount": 279.3,
"currencyCode": "INR"
},
"buyLink": "http://books.google.co.in/books?id=An4_e3Cr3zAC&dq=game&hl=&buy=&source=gbs_api",
"offers": [
{
"finskyOfferType": 1,
"listPrice": {
"amountInMicros": 3.99E8,
"currencyCode": "INR"
},
"retailPrice": {
"amountInMicros": 2.793E8,
"currencyCode": "INR"
}
}
]
},
"accessInfo": {
"country": "IN",
"viewability": "PARTIAL",
"embeddable": true,
"publicDomain": false,
"textToSpeechPermission": "ALLOWED",
"epub": {
"isAvailable": true,
"acsTokenLink": "http://books.goo"
},
"pdf": {
"isAvailable": true,
"acsTokenLink": "http://books.google.co.in/books/download/The_Rules_of_the_Game-sample-pdf.acsm?id=An4_e3Cr3zAC&format=pdf&output=acs4_fulfillment_token&dl_type=sample&source=gbs_api"
},
"webReaderLink": "http://books.google.co.in/books/reader?id=An4_e3Cr3zAC&hl=&printsec=frontcover&output=reader&source=gbs_api",
"accessViewStatus": "SAMPLE",
"quoteSharingAllowed": false
},
"searchInfo": {
"textSnippet": "He's tested the specific material."
}
}
]
}
Here is the stacktrace form logcat. https://codeshare.io/Ag78v
Replace your Items class with below:
public class Items
{
private SaleInfo saleInfo;
private String id;
private SearchInfo searchInfo;
private String etag;
private VolumeInfo volumeInfo;
private String selfLink;
private AccessInfo accessInfo;
private String kind;
public SaleInfo getSaleInfo ()
{
return saleInfo;
}
public void setSaleInfo (SaleInfo saleInfo)
{
this.saleInfo = saleInfo;
}
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
public SearchInfo getSearchInfo ()
{
return searchInfo;
}
public void setSearchInfo (SearchInfo searchInfo)
{
this.searchInfo = searchInfo;
}
public String getEtag ()
{
return etag;
}
public void setEtag (String etag)
{
this.etag = etag;
}
public VolumeInfo getVolumeInfo() {
return volumeInfo;
}
public void setVolumeInfo(VolumeInfo volumeInfo) {
this.volumeInfo = volumeInfo;
}
public String getSelfLink ()
{
return selfLink;
}
public void setSelfLink (String selfLink)
{
this.selfLink = selfLink;
}
public AccessInfo getAccessInfo ()
{
return accessInfo;
}
public void setAccessInfo (AccessInfo accessInfo)
{
this.accessInfo = accessInfo;
}
public String getKind ()
{
return kind;
}
public void setKind (String kind)
{
this.kind = kind;
}
}
You are not using the serializedName annotation. Use it as follows in your model.
public class Items
{
#SerializedName("Your-key-from JSON Response")
private SaleInfo saleInfo;
#SerializedName("Your-key-from JSON Response")
private String id;
#SerializedName("Your-key-from JSON Response")
private SearchInfo searchInfo;
#SerializedName("Your-key-from JSON Response")
private String etag;
#SerializedName("Your-key-from JSON Response")
private VolumeInfo volumeInfo;
#SerializedName("Your-key-from JSON Response")
private String selfLink;
#SerializedName("Your-key-from JSON Response")
private AccessInfo accessInfo;
#SerializedName("Your-key-from JSON Response")
private String kind;
public SaleInfo getSaleInfo ()
{
return saleInfo;
}
public void setSaleInfo (SaleInfo saleInfo)
{
this.saleInfo = saleInfo;
}
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
}
One of Your ListItem VolumeInfo have null value for title. By default Gson wont parse null value. But you can make to ignore null values when parsing. by doing the following.
Gson gson = new GsonBuilder().serializeNulls().create();
Try this.
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();
}
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;
}
}