JSON Exception - No value for in Android - java

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.

Related

I am gettion json response in Object but i want to be in Json Array

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()
}

Retrofit + Observable - Expected BEGIN_ARRAY but was BEGIN_OBJECT

I'm trying to use New York Times API with Retrofit using Observable. But I'm getting this error when trying to use datas.
Can someone help me see where I'm wrong, please ?
Here is my ApiServices interface:
#GET("svc/topstories/v2/home.json?api-key=HiddenApiKeyJustForThisMessage")
Observable<TopStoryResult> getTopStories();
#GET("svc/topstories/v2/home.json?api-key=HiddenApiKeyJustForThisMessage")
Observable<List<NewsItem>> getResults();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.nytimes.com/")
.addConverterFactory(GsonConverterFactory.create(new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
Here is my ApiStreams class
public static Observable<TopStoryResult> streamFetchTopStories(){
ApiServices mApiServices = ApiServices.retrofit.create(ApiServices.class);
return mApiServices.getTopStories()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.timeout(10, TimeUnit.SECONDS);
}
public static Observable<List<NewsItem>> streamFetchNews(){
ApiServices mApiServices = ApiServices.retrofit.create(ApiServices.class);
return mApiServices.getResults()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.timeout(10, TimeUnit.SECONDS);
}
And this is what I'm trying to do in my MainActivity. For now I just want to display in a TextView the list of each Title...
//------------------------
// Update UI
//------------------------
private void updateUIWhenStartingHttpRequest() {
this.textView.setText("Downloading...");
}
private void updateUIWhenStopingHttpRequest(String response) {
this.textView.setText(response);
}
//------------------------
// Rx Java
//------------------------
private void executeRequestWithRetrofit(){
this.updateUIWhenStartingHttpRequest();
this.disposable = ApiStreams.streamFetchNews()
.subscribeWith(new DisposableObserver<List<NewsItem>>(){
#Override
public void onNext(List<NewsItem> topStories) {
Log.e("TAG", "On Next");
updateUIWithResult(topStories);
}
#Override
public void onError(Throwable e) {
Log.e("ERROR", Log.getStackTraceString(e));
}
#Override
public void onComplete() {
Log.e("TAG", "On Complete !");
}
});
}
private void updateUIWithResult(List<NewsItem> newsItemList){
StringBuilder mStringBuilder = new StringBuilder();
for (NewsItem news : newsItemList){
Log.e("TAG", "UPDATE UI" + news.getTitle());
mStringBuilder.append("- " + news.getTitle() + "\n");
}
updateUIWhenStopingHttpRequest(mStringBuilder.toString());
}
[EDIT]
There are my two models for TopStories and NewsItem
TopStories:
private String status;
private String copyright;
private String section;
private String lastUpdated;
private Integer numResults;
private List<NewsItem> results = null;
public String getStatus() {return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getCopyright() {
return copyright;
}
public void setCopyright(String copyright) {
this.copyright = copyright;
}
public String getSection() {
return section;
}
public void setSection(String section) {
this.section = section;
}
public String getLastUpdated() {
return lastUpdated;
}
public void setLastUpdated(String lastUpdated) {
this.lastUpdated = lastUpdated;
}
public Integer getNumResults() {
return numResults;
}
public void setNumResults(Integer numResults) {
this.numResults = numResults;
}
public List<NewsItem> getResults() {
return results;
}
public void setResults(List<NewsItem> results) {
this.results = results;
}
NewsItem:
private String section;
private String subsection;
private String title;
private String url;
private String byline;
private String updated_date;
private String created_date;
private String published_date;
private String material_type_facet;
private String kicker;
#SerializedName("abstract")
private String abstract_string;
private List<Multimedia> multimedia;
private transient String des_facet;
private transient String org_facet;
private transient String per_facet;
private transient String geo_facet;
public NewsItem() {
}
public NewsItem(String url) {
this.url = url;
}
public NewsItem(String section, String subsection, String title, String url, String byline, String updated_date, String created_date, String published_date, String material_type_facet, String kicker) {
this.section = section;
this.subsection = subsection;
this.title = title;
this.url = url;
this.byline = byline;
this.updated_date = updated_date;
this.created_date = created_date;
this.published_date = published_date;
this.material_type_facet = material_type_facet;
this.kicker = kicker;
}
public String getSection() {
return section;
}
public void setSection(String section) {
this.section = section;
}
public String getSubsection() {
return subsection;
}
public void setSubsection(String subsection) {
this.subsection = subsection;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getByline() {
return byline;
}
public void setByline(String byline) {
this.byline = byline;
}
public String getUpdated_date() {
return updated_date;
}
public void setUpdated_date(String updated_date) {
this.updated_date = updated_date;
}
public String getCreated_date() {
return created_date;
}
public void setCreated_date(String created_date) {
this.created_date = created_date;
}
public String getPublished_date() {
return published_date;
}
public void setPublished_date(String published_date) {
this.published_date = published_date;
}
public String getMaterial_type_facet() {
return material_type_facet;
}
public void setMaterial_type_facet(String material_type_facet) {
this.material_type_facet = material_type_facet;
}
public String getKicker() {
return kicker;
}
public void setKicker(String kicker) {
this.kicker = kicker;
}
public String getAbstract() {
return abstract_string;
}
public void setAbstract(String abstract_string) {
this.abstract_string = abstract_string;
}
public List<Multimedia> getMultimedia() {
return multimedia;
}
public void setMultimedia(List<Multimedia> multimedia) {
this.multimedia = multimedia;
}
public String getDes_facet() {
return des_facet;
}
public void setDes_facet(String des_facet) {
this.des_facet = des_facet;
}
public String getOrg_facet() {
return org_facet;
}
public void setOrg_facet(String org_facet) {
this.org_facet = org_facet;
}
public String getPer_facet() {
return per_facet;
}
public void setPer_facet(String per_facet) {
this.per_facet = per_facet;
}
public String getGeo_facet() {
return geo_facet;
}
public void setGeo_facet(String geo_facet) {
this.geo_facet = geo_facet;
}
Here is what the JSON looks like:
JSON
First when I tried this one with Github user API, it works fine. But I can't figure out where I'm wrong there...
Is anybody can help me please ?
Thanks a lot !
Expected BEGIN_ARRAY but was BEGIN_OBJECT
this means you are trying to a get a JSON Array as a List in JAVA but the api sent you a JSON OBJECT. So I cannot gather enough information but if I have to guess you should change this
#GET("svc/topstories/v2/home.json?api-key=HiddenApiKeyJustForThisMessage")
Observable<List<NewsItem>> getResults();
to
#GET("svc/topstories/v2/home.json?api-key=HiddenApiKeyJustForThisMessage")
Observable<NewsItemObject> getResults();
NewsItemObject is the Class that wraps NewsItem
In your ApiServices interface you expect that getResults() returns Observable<List<NewsItem>>. Based on JSON you getting back this is not gonna work, because your root JSON element is Object, not an Array.
You have to create new wrapper Class (ResultsWrapper) with "results" field type of List<NewsItem>. Your method in ApiServices interface will then be:
#GET("svc/topstories/v2/home.json?api-key=HiddenApiKeyJustForThisMessage")
Observable<ResultsWrapper> getResults();
That is what "Expected BEGIN_ARRAY but was BEGIN_OBJECT" says to you.

Assigning multiple Retrofit response values to an arraylist

I'm struggling to implement a solution to retrieve multiple values from my api response ( https://www.thecocktaildb.com/api/json/v1/1/lookup.php?i=13060 ) and assign specific values to an array. Specifically values, strIngredient1, strIngredient2, strIngredient3 etc...
At present i created a POJO cocktail class as follows:
public class Cocktail implements Serializable {
#SerializedName("idDrink")
#Expose
private String idDrink;
#SerializedName("strDrink")
#Expose
private String strDrink;
#SerializedName("strVideo")
#Expose
private Object strVideo;
#SerializedName("strCategory")
#Expose
private String strCategory;
#SerializedName("strIBA")
#Expose
private Object strIBA;
#SerializedName("strAlcoholic")
#Expose
private String strAlcoholic;
#SerializedName("strGlass")
#Expose
private String strGlass;
#SerializedName("strInstructions")
#Expose
private String strInstructions;
#SerializedName("strDrinkThumb")
#Expose
private String strDrinkThumb;
#SerializedName("strIngredient1")
#Expose
private String strIngredient1;
#SerializedName("strIngredient2")
#Expose
private String strIngredient2;
#SerializedName("strIngredient3")
#Expose
private String strIngredient3;
#SerializedName("strIngredient4")
#Expose
private String strIngredient4;
#SerializedName("strIngredient5")
#Expose
private String strIngredient5;
#SerializedName("strIngredient6")
#Expose
private String strIngredient6;
#SerializedName("strIngredient7")
#Expose
private String strIngredient7;
#SerializedName("strIngredient8")
#Expose
private String strIngredient8;
#SerializedName("strIngredient9")
#Expose
private String strIngredient9;
#SerializedName("strIngredient10")
#Expose
private String strIngredient10;
#SerializedName("strIngredient11")
#Expose
private String strIngredient11;
#SerializedName("strIngredient12")
#Expose
private String strIngredient12;
#SerializedName("strIngredient13")
#Expose
private String strIngredient13;
#SerializedName("strIngredient14")
#Expose
private String strIngredient14;
#SerializedName("strIngredient15")
#Expose
private String strIngredient15;
#SerializedName("strMeasure1")
#Expose
private String strMeasure1;
#SerializedName("strMeasure2")
#Expose
private String strMeasure2;
#SerializedName("strMeasure3")
#Expose
private String strMeasure3;
#SerializedName("strMeasure4")
#Expose
private String strMeasure4;
#SerializedName("strMeasure5")
#Expose
private String strMeasure5;
#SerializedName("strMeasure6")
#Expose
private String strMeasure6;
#SerializedName("strMeasure7")
#Expose
private String strMeasure7;
#SerializedName("strMeasure8")
#Expose
private String strMeasure8;
#SerializedName("strMeasure9")
#Expose
private String strMeasure9;
#SerializedName("strMeasure10")
#Expose
private String strMeasure10;
#SerializedName("strMeasure11")
#Expose
private String strMeasure11;
#SerializedName("strMeasure12")
#Expose
private String strMeasure12;
#SerializedName("strMeasure13")
#Expose
private String strMeasure13;
#SerializedName("strMeasure14")
#Expose
private String strMeasure14;
#SerializedName("strMeasure15")
#Expose
private String strMeasure15;
#SerializedName("dateModified")
#Expose
private String dateModified;
public String getIdDrink() {
return idDrink;
}
public void setIdDrink(String idDrink) {
this.idDrink = idDrink;
}
public String getStrDrink() {
return strDrink;
}
public void setStrDrink(String strDrink) {
this.strDrink = strDrink;
}
public Object getStrVideo() {
return strVideo;
}
public void setStrVideo(Object strVideo) {
this.strVideo = strVideo;
}
public String getStrCategory() {
return strCategory;
}
public void setStrCategory(String strCategory) {
this.strCategory = strCategory;
}
public Object getStrIBA() {
return strIBA;
}
public void setStrIBA(Object strIBA) {
this.strIBA = strIBA;
}
public String getStrAlcoholic() {
return strAlcoholic;
}
public void setStrAlcoholic(String strAlcoholic) {
this.strAlcoholic = strAlcoholic;
}
public String getStrGlass() {
return strGlass;
}
public void setStrGlass(String strGlass) {
this.strGlass = strGlass;
}
public String getStrInstructions() {
return strInstructions;
}
public void setStrInstructions(String strInstructions) {
this.strInstructions = strInstructions;
}
public String getStrDrinkThumb() {
return strDrinkThumb;
}
public void setStrDrinkThumb(String strDrinkThumb) {
this.strDrinkThumb = strDrinkThumb;
}
public String getStrIngredient1() {
return strIngredient1;
}
public void setStrIngredient1(String strIngredient1) {
this.strIngredient1 = strIngredient1;
}
public String getStrIngredient2() {
return strIngredient2;
}
public void setStrIngredient2(String strIngredient2) {
this.strIngredient2 = strIngredient2;
}
public String getStrIngredient3() {
return strIngredient3;
}
public void setStrIngredient3(String strIngredient3) {
this.strIngredient3 = strIngredient3;
}
public String getStrIngredient4() {
return strIngredient4;
}
public void setStrIngredient4(String strIngredient4) {
this.strIngredient4 = strIngredient4;
}
public String getStrIngredient5() {
return strIngredient5;
}
public void setStrIngredient5(String strIngredient5) {
this.strIngredient5 = strIngredient5;
}
public String getStrIngredient6() {
return strIngredient6;
}
public void setStrIngredient6(String strIngredient6) {
this.strIngredient6 = strIngredient6;
}
public String getStrIngredient7() {
return strIngredient7;
}
public void setStrIngredient7(String strIngredient7) {
this.strIngredient7 = strIngredient7;
}
public String getStrIngredient8() {
return strIngredient8;
}
public void setStrIngredient8(String strIngredient8) {
this.strIngredient8 = strIngredient8;
}
public String getStrIngredient9() {
return strIngredient9;
}
public void setStrIngredient9(String strIngredient9) {
this.strIngredient9 = strIngredient9;
}
public String getStrIngredient10() {
return strIngredient10;
}
public void setStrIngredient10(String strIngredient10) {
this.strIngredient10 = strIngredient10;
}
public String getStrIngredient11() {
return strIngredient11;
}
public void setStrIngredient11(String strIngredient11) {
this.strIngredient11 = strIngredient11;
}
public String getStrIngredient12() {
return strIngredient12;
}
public void setStrIngredient12(String strIngredient12) {
this.strIngredient12 = strIngredient12;
}
public String getStrIngredient13() {
return strIngredient13;
}
public void setStrIngredient13(String strIngredient13) {
this.strIngredient13 = strIngredient13;
}
public String getStrIngredient14() {
return strIngredient14;
}
public void setStrIngredient14(String strIngredient14) {
this.strIngredient14 = strIngredient14;
}
public String getStrIngredient15() {
return strIngredient15;
}
public void setStrIngredient15(String strIngredient15) {
this.strIngredient15 = strIngredient15;
}
public String getStrMeasure1() {
return strMeasure1;
}
public void setStrMeasure1(String strMeasure1) {
this.strMeasure1 = strMeasure1;
}
public String getStrMeasure2() {
return strMeasure2;
}
public void setStrMeasure2(String strMeasure2) {
this.strMeasure2 = strMeasure2;
}
public String getStrMeasure3() {
return strMeasure3;
}
public void setStrMeasure3(String strMeasure3) {
this.strMeasure3 = strMeasure3;
}
public String getStrMeasure4() {
return strMeasure4;
}
public void setStrMeasure4(String strMeasure4) {
this.strMeasure4 = strMeasure4;
}
public String getStrMeasure5() {
return strMeasure5;
}
public void setStrMeasure5(String strMeasure5) {
this.strMeasure5 = strMeasure5;
}
public String getStrMeasure6() {
return strMeasure6;
}
public void setStrMeasure6(String strMeasure6) {
this.strMeasure6 = strMeasure6;
}
public String getStrMeasure7() {
return strMeasure7;
}
public void setStrMeasure7(String strMeasure7) {
this.strMeasure7 = strMeasure7;
}
public String getStrMeasure8() {
return strMeasure8;
}
public void setStrMeasure8(String strMeasure8) {
this.strMeasure8 = strMeasure8;
}
public String getStrMeasure9() {
return strMeasure9;
}
public void setStrMeasure9(String strMeasure9) {
this.strMeasure9 = strMeasure9;
}
public String getStrMeasure10() {
return strMeasure10;
}
public void setStrMeasure10(String strMeasure10) {
this.strMeasure10 = strMeasure10;
}
public String getStrMeasure11() {
return strMeasure11;
}
public void setStrMeasure11(String strMeasure11) {
this.strMeasure11 = strMeasure11;
}
public String getStrMeasure12() {
return strMeasure12;
}
public void setStrMeasure12(String strMeasure12) {
this.strMeasure12 = strMeasure12;
}
public String getStrMeasure13() {
return strMeasure13;
}
public void setStrMeasure13(String strMeasure13) {
this.strMeasure13 = strMeasure13;
}
public String getStrMeasure14() {
return strMeasure14;
}
public void setStrMeasure14(String strMeasure14) {
this.strMeasure14 = strMeasure14;
}
public String getStrMeasure15() {
return strMeasure15;
}
public void setStrMeasure15(String strMeasure15) {
this.strMeasure15 = strMeasure15;
}
public String getDateModified() {
return dateModified;
}
public void setDateModified(String dateModified) {
this.dateModified = dateModified;
}
And my API call is as follows:
#Override
protected Cocktail doInBackground(Cocktail... cocktails) {
Call<Cocktails> call = mApiService.getCocktail(id);
try {
Response<Cocktails> response = call.execute();
this.cocktails = response.body();
this.cocktail = this.cocktails.getCocktail().get(0);
Log.i(TAG, "Success: " + response.body().toString());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e);
e.printStackTrace();
} catch (IllegalStateException e) {
Log.e(TAG, "IllegalStateException: " + e);
e.printStackTrace();
}
return cocktail;
}
I know enough to realise that a large number of variables, ingredients and measures (many of which are empty) is the wrong approach but i'm struggling to find a solution with retrofit to create an array of these values. I've not found any way to assign multiple SerializedNames to a single array variable?
The option that jumps out at me is looping through the response pulling out the key values in onSuccess but this seems to go against the simplicity of using retrofit?

Storing JSON object using Volley

This is the structure of the JSON I need to Load,
{
"readme_0" : "THIS JSON IS THE RESULT OF YOUR SEARCH QUERY - THERE IS NO WEB PAGE WHICH SHOWS THE RESULT!",
"readme_1" : "loklak.org is the framework for a message search system, not the portal, read: http://loklak.org/about.html#notasearchportal",
"readme_2" : "This is supposed to be the back-end of a search portal. For the api, see http://loklak.org/api.html",
"readme_3" : "Parameters q=(query), source=(cache|backend|twitter|all), callback=p for jsonp, maximumRecords=(message count), minified=(true|false)",
"search_metadata" : {
"itemsPerPage" : "100",
"count" : "100",
"count_twitter_all" : 0,
"count_twitter_new" : 100,
"count_backend" : 0,
"count_cache" : 78780,
"hits" : 78780,
"period" : 3066,
"query" : "apple",
"client" : "180.215.121.78",
"time" : 5219,
"servicereduction" : "false",
"scraperInfo" : "http://45.55.245.191:9000,local"
},
"statuses" : [ {
"created_at" : "2016-01-09T12:11:38.000Z",
"screen_name" : "arifazmi92",
"text" : "Perhaps I shouldn't have eaten that pisang goreng cheese perisa green apple. <img class=\"Emoji Emoji--forText\" src=\"https://abs.twimg.com/emoji/v2/72x72/1f605.png\" draggable=\"false\" alt=\"😅\" title=\"Smiling face with open mouth and cold sweat\" aria-label=\"Emoji: Smiling face with open mouth and cold sweat\"><img class=\"Emoji Emoji--forText\" src=\"https://abs.twimg.com/emoji/v2/72x72/1f605.png\" draggable=\"false\" alt=\"😅\" title=\"Smiling face with open mouth and cold sweat\" aria-label=\"Emoji: Smiling face with open mouth and cold sweat\"><img class=\"Emoji Emoji--forText\" src=\"https://abs.twimg.com/emoji/v2/72x72/1f605.png\" draggable=\"false\" alt=\"😅\" title=\"Smiling face with open mouth and cold sweat\" aria-label=\"Emoji: Smiling face with open mouth and cold sweat\">",
"link" : "https://twitter.com/arifazmi92/status/685796067082813440",
"id_str" : "685796067082813440",
"source_type" : "TWITTER",
"provider_type" : "SCRAPED",
"retweet_count" : 0,
"favourites_count" : 0,
"images" : [ ],
"images_count" : 0,
"audio" : [ ],
"audio_count" : 0,
"videos" : [ ],
"videos_count" : 0,
"place_name" : "Bandar Shah Alam, Selangor",
"place_id" : "9be3b0eca6c21f6c",
"place_context" : "FROM",
"place_country" : "Malaysia",
"place_country_code" : "MY",
"place_country_center" : [ -59.30559537806809, 3.4418498787292435 ],
"location_point" : [ 101.53280621465888, 3.0850698533863863 ],
"location_radius" : 0,
"location_mark" : [ 101.52542227271437, 3.0911033774188725 ],
"location_source" : "PLACE",
"hosts" : [ "abs.twimg.com" ],
"hosts_count" : 1,
"links" : [ "https://abs.twimg.com/emoji/v2/72x72/1f605.png\"", "https://abs.twimg.com/emoji/v2/72x72/1f605.png\"", "https://abs.twimg.com/emoji/v2/72x72/1f605.png\"" ],
"links_count" : 3,
"mentions" : [ ],
"mentions_count" : 0,
"hashtags" : [ ],
"hashtags_count" : 0,
"without_l_len" : 626,
"without_lu_len" : 626,
"without_luh_len" : 626,
"user" : {
"screen_name" : "arifazmi92",
"user_id" : "44503967",
"name" : "Arif Azmi",
"profile_image_url_https" : "https://pbs.twimg.com/profile_images/685788990004301824/NbFnnLuO_bigger.jpg",
"appearance_first" : "2016-01-09T12:11:57.933Z",
"appearance_latest" : "2016-01-09T12:11:57.933Z"
}
}
} ],
"aggregations" : { }
}
And these are my POJO classes that I've generated:
MainPojo.class
public class MainPojo
{
#SerializedName("readme_0")
#Expose
private String readme0;
#SerializedName("readme_1")
#Expose
private String readme1;
#SerializedName("readme_2")
#Expose
private String readme2;
#SerializedName("readme_3")
#Expose
private String readme3;
#SerializedName("search_metadata")
#Expose
private SearchMetadata searchMetadata;
#SerializedName("statuses")
#Expose
private List<Status> statuses = new ArrayList<Status>();
#SerializedName("aggregations")
#Expose
private Aggregations aggregations;
public String getReadme0() {
return readme0;
}
public void setReadme0(String readme0) {
this.readme0 = readme0;
}
public String getReadme1() {
return readme1;
}
public void setReadme1(String readme1) {
this.readme1 = readme1;
}
public String getReadme2() {
return readme2;
}
public void setReadme2(String readme2) {
this.readme2 = readme2;
}
public String getReadme3() {
return readme3;
}
public void setReadme3(String readme3) {
this.readme3 = readme3;
}
public SearchMetadata getSearchMetadata() {
return searchMetadata;
}
public void setSearchMetadata(SearchMetadata searchMetadata) {
this.searchMetadata = searchMetadata;
}
public List<Status> getStatuses() {
return statuses;
}
public void setStatuses(List<Status> statuses) {
this.statuses = statuses;
}
public Aggregations getAggregations() {
return aggregations;
}
public void setAggregations(Aggregations aggregations) {
this.aggregations = aggregations;
}
}
Status.class
public class Status
{
#SerializedName("created_at")
#Expose
private String createdAt;
#SerializedName("screen_name")
#Expose
private String screenName;
#SerializedName("text")
#Expose
private String text;
#SerializedName("link")
#Expose
private String link;
#SerializedName("id_str")
#Expose
private String idStr;
#SerializedName("source_type")
#Expose
private String sourceType;
#SerializedName("provider_type")
#Expose
private String providerType;
#SerializedName("retweet_count")
#Expose
private Integer retweetCount;
#SerializedName("favourites_count")
#Expose
private Integer favouritesCount;
#SerializedName("images")
#Expose
private List<Object> images = new ArrayList<Object>();
#SerializedName("images_count")
#Expose
private Integer imagesCount;
#SerializedName("audio")
#Expose
private List<Object> audio = new ArrayList<Object>();
#SerializedName("audio_count")
#Expose
private Integer audioCount;
#SerializedName("videos")
#Expose
private List<Object> videos = new ArrayList<Object>();
#SerializedName("videos_count")
#Expose
private Integer videosCount;
#SerializedName("place_name")
#Expose
private String placeName;
#SerializedName("place_id")
#Expose
private String placeId;
#SerializedName("place_context")
#Expose
private String placeContext;
#SerializedName("location_point")
#Expose
private List<Double> locationPoint = new ArrayList<Double>();
#SerializedName("location_radius")
#Expose
private Integer locationRadius;
#SerializedName("location_mark")
#Expose
private List<Double> locationMark = new ArrayList<Double>();
#SerializedName("location_source")
#Expose
private String locationSource;
#SerializedName("hosts")
#Expose
private List<String> hosts = new ArrayList<String>();
#SerializedName("hosts_count")
#Expose
private Integer hostsCount;
#SerializedName("links")
#Expose
private List<String> links = new ArrayList<String>();
#SerializedName("links_count")
#Expose
private Integer linksCount;
#SerializedName("mentions")
#Expose
private List<Object> mentions = new ArrayList<Object>();
#SerializedName("mentions_count")
#Expose
private Integer mentionsCount;
#SerializedName("hashtags")
#Expose
private List<Object> hashtags = new ArrayList<Object>();
#SerializedName("hashtags_count")
#Expose
private Integer hashtagsCount;
#SerializedName("without_l_len")
#Expose
private Integer withoutLLen;
#SerializedName("without_lu_len")
#Expose
private Integer withoutLuLen;
#SerializedName("without_luh_len")
#Expose
private Integer withoutLuhLen;
#SerializedName("user")
#Expose
private User user;
#SerializedName("provider_hash")
#Expose
private String providerHash;
#SerializedName("classifier_language")
#Expose
private String classifierLanguage;
#SerializedName("classifier_language_probability")
#Expose
private Double classifierLanguageProbability;
public String getCreatedAt() {
return createdAt;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
public String getScreenName() {
return screenName;
}
public void setScreenName(String screenName) {
this.screenName = screenName;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getIdStr() {
return idStr;
}
public void setIdStr(String idStr) {
this.idStr = idStr;
}
public String getSourceType() {
return sourceType;
}
public void setSourceType(String sourceType) {
this.sourceType = sourceType;
}
public String getProviderType() {
return providerType;
}
public void setProviderType(String providerType) {
this.providerType = providerType;
}
public Integer getRetweetCount() {
return retweetCount;
}
public void setRetweetCount(Integer retweetCount) {
this.retweetCount = retweetCount;
}
public Integer getFavouritesCount() {
return favouritesCount;
}
public void setFavouritesCount(Integer favouritesCount) {
this.favouritesCount = favouritesCount;
}
public List<Object> getImages() {
return images;
}
public void setImages(List<Object> images) {
this.images = images;
}
public Integer getImagesCount() {
return imagesCount;
}
public void setImagesCount(Integer imagesCount) {
this.imagesCount = imagesCount;
}
public List<Object> getAudio() {
return audio;
}
public void setAudio(List<Object> audio) {
this.audio = audio;
}
public Integer getAudioCount() {
return audioCount;
}
public void setAudioCount(Integer audioCount) {
this.audioCount = audioCount;
}
public List<Object> getVideos() {
return videos;
}
public void setVideos(List<Object> videos) {
this.videos = videos;
}
public Integer getVideosCount() {
return videosCount;
}
public void setVideosCount(Integer videosCount) {
this.videosCount = videosCount;
}
public String getPlaceName() {
return placeName;
}
public void setPlaceName(String placeName) {
this.placeName = placeName;
}
public String getPlaceId() {
return placeId;
}
public void setPlaceId(String placeId) {
this.placeId = placeId;
}
public String getPlaceContext() {
return placeContext;
}
public void setPlaceContext(String placeContext) {
this.placeContext = placeContext;
}
public List<Double> getLocationPoint() {
return locationPoint;
}
public void setLocationPoint(List<Double> locationPoint) {
this.locationPoint = locationPoint;
}
public Integer getLocationRadius() {
return locationRadius;
}
public void setLocationRadius(Integer locationRadius) {
this.locationRadius = locationRadius;
}
public List<Double> getLocationMark() {
return locationMark;
}
public void setLocationMark(List<Double> locationMark) {
this.locationMark = locationMark;
}
public String getLocationSource() {
return locationSource;
}
public void setLocationSource(String locationSource) {
this.locationSource = locationSource;
}
public List<String> getHosts() {
return hosts;
}
public void setHosts(List<String> hosts) {
this.hosts = hosts;
}
public Integer getHostsCount() {
return hostsCount;
}
public void setHostsCount(Integer hostsCount) {
this.hostsCount = hostsCount;
}
public List<String> getLinks() {
return links;
}
public void setLinks(List<String> links) {
this.links = links;
}
public Integer getLinksCount() {
return linksCount;
}
public void setLinksCount(Integer linksCount) {
this.linksCount = linksCount;
}
public List<Object> getMentions() {
return mentions;
}
public void setMentions(List<Object> mentions) {
this.mentions = mentions;
}
public Integer getMentionsCount() {
return mentionsCount;
}
public void setMentionsCount(Integer mentionsCount) {
this.mentionsCount = mentionsCount;
}
public List<Object> getHashtags() {
return hashtags;
}
public void setHashtags(List<Object> hashtags) {
this.hashtags = hashtags;
}
public Integer getHashtagsCount() {
return hashtagsCount;
}
public void setHashtagsCount(Integer hashtagsCount) {
this.hashtagsCount = hashtagsCount;
}
public Integer getWithoutLLen() {
return withoutLLen;
}
public void setWithoutLLen(Integer withoutLLen) {
this.withoutLLen = withoutLLen;
}
public Integer getWithoutLuLen() {
return withoutLuLen;
}
public void setWithoutLuLen(Integer withoutLuLen) {
this.withoutLuLen = withoutLuLen;
}
public Integer getWithoutLuhLen() {
return withoutLuhLen;
}
public void setWithoutLuhLen(Integer withoutLuhLen) {
this.withoutLuhLen = withoutLuhLen;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getProviderHash() {
return providerHash;
}
public void setProviderHash(String providerHash) {
this.providerHash = providerHash;
}
public String getClassifierLanguage() {
return classifierLanguage;
}
public void setClassifierLanguage(String classifierLanguage) {
this.classifierLanguage = classifierLanguage;
}
public Double getClassifierLanguageProbability() {
return classifierLanguageProbability;
}
public void setClassifierLanguageProbability(Double classifierLanguageProbability) {
this.classifierLanguageProbability = classifierLanguageProbability;
}
}
User.java
public class User {
#SerializedName("screen_name")
#Expose
private String screenName;
#SerializedName("user_id")
#Expose
private String userId;
#SerializedName("name")
#Expose
private String name;
#SerializedName("profile_image_url_https")
#Expose
private String profileImageUrlHttps;
#SerializedName("appearance_first")
#Expose
private String appearanceFirst;
#SerializedName("appearance_latest")
#Expose
private String appearanceLatest;
public String getScreenName() {
return screenName;
}
public void setScreenName(String screenName) {
this.screenName = screenName;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getProfileImageUrlHttps() {
return profileImageUrlHttps;
}
public void setProfileImageUrlHttps(String profileImageUrlHttps) {
this.profileImageUrlHttps = profileImageUrlHttps;
}
public String getAppearanceFirst() {
return appearanceFirst;
}
public void setAppearanceFirst(String appearanceFirst) {
this.appearanceFirst = appearanceFirst;
}
public String getAppearanceLatest() {
return appearanceLatest;
}
public void setAppearanceLatest(String appearanceLatest) {
this.appearanceLatest = appearanceLatest;
}
}
Aggregations.class
public class Aggregations {
}
And finally, this is the code I use to read the JSON and store as JSON objects,
SharedPreferences Tempx = getSharedPreferences("ActivitySession", Context.MODE_PRIVATE);
SharedPreferences.Editor edx = Tempx.edit();
edx.putString("GSON_FEED", response.toString());
edx.apply();
Gson gson = new Gson();
JsonParser parser = new JsonParser();
try{
JsonArray jArray = parser.parse(Tempx.getString("GSON_FEED","")).getAsJsonArray();
for(JsonElement obj : jArray )
{
MainPojo cse = gson.fromJson( obj , MainPojo.class);
TweetList.add(cse);
}
}catch(Throwable e) {
JsonElement obj = parser.parse(Tempx.getString("GSON_FEED","")).getAsJsonObject();
MainPojo cse = gson.fromJson( obj , MainPojo.class);
TweetList.add(cse);
}
Though I am able to log the JSON as String, I don't know if I am storing it the wrong way, any help will be much appreciated, Thanks!
You could define a custom deserializer and register a type adapter with GSON. Also
why are you using this:
JsonArray jArray = parser.parse(Tempx.getString("GSON_FEED","")).getAsJsonArray();
.. when you intend to use GSON for deserialization? You could just do it in your deserializer.
https://sites.google.com/site/gson/gson-user-guide#TOC-Custom-Serialization-and-Deserialization
EG:
public class FooDeserializer implements JsonDeserializer<Foos>
{
#Override public Foos deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException
{
JsonObject jsonObject = json.getAsJsonObject();
JsonArray statusArray = jsonObject.get("statuses").getAsJsonArray();
Foos result = new Foos();
ArrayList fooArray = new ArrayList<>;
for (JsonElement e : statusArray) {
fooArray.add(new Foo());
}
result.setFoos(fooArray);
return result;
}
}

Mybatis There is no getter for property

I'm working with Mybatis to batch insert data,specifically my parameterType is a class,which has a List property,so I use foreach to do the traversal.But it didn't work,here are the debug and codes.Thanks.
DEBUG
here is the sql:
<insert id="batchInsertSn" parameterType="domain.collectSn.IbSnTransit">
insert into
ib_sn_transit (
sn, inbound_no, container_no,
goods_no,goods_name, owner_no,
owner_name,create_user,update_user,
create_time,update_time,yn,
org_no,org_name,distribute_no,
warehouse_no,receiving_no,supplier_no
,out_wave_no)
values
<foreach collection="snList" item="item" index="index" separator="," >
(
#{item.sn,jdbcType=VARCHAR}, #{inboundNo,jdbcType=VARCHAR}, #{containerNo,jdbcType=VARCHAR},
#{goodsNo,jdbcType=VARCHAR},#{goodsName,jdbcType=VARCHAR},#{ownerNo,jdbcType=VARCHAR},
#{ownerName,jdbcType=VARCHAR}, #{createUser,jdbcType=VARCHAR}, #{updateUser,jdbcType=VARCHAR},
now(),now(),#{yn,jdbcType=TINYINT},
#{orgNo,jdbcType=VARCHAR},#{orgName,jdbcType=VARCHAR},#{distributeNo,jdbcType=VARCHAR},
#{warehouseNo,jdbcType=VARCHAR},#{receivingNo,jdbcType=VARCHAR},#{supplierNo,jdbcType=VARCHAR}
,#{outWaveNo,jdbcType=VARCHAR}
)
</foreach>
</insert>
here is the class
public class IbSnTransit {
private String outWaveNo;
private String queryUser;
private String finishFlag;
private Integer id;
private String inboundNo;
private String sn;
private String snStart;
private String snEnd;
private String containerNo;
private String goodsNo;
private String goodsName;
private String ownerNo;
private String ownerName;
private String createUser;
private Date createTime;
private String updateUser;
private Date updateTime;
private Integer yn;
private String orgNo;
private String orgName;
private String distributeNo;
private String warehouseNo;
private String receivingNo;
private String supplierNo;
private List<String> snList;
public String getSupplierNo() {
return supplierNo;
}
public void setSupplierNo(String supplierNo) {
this.supplierNo = supplierNo;
}
public Integer getId() {
return id;
}
public void setId(Integer id){
this.id = id;
}
public String getOwnerName() {
return ownerName;
}
public void setOwnerName(String ownerName) {
this.ownerName = ownerName;
}
public String getOrgName() {
return orgName;
}
public void setOrgName(String orgName) {
this.orgName = orgName;
}
public String getSn() {
return sn;
}
public void setSn(String sn){
this.sn = sn;
}
public String getInboundNo() {
return inboundNo;
}
public void setInboundNo(String inboundNo) {
this.inboundNo = inboundNo;
}
public String getGoodsNo() {
return goodsNo;
}
public void setGoodsNo(String goodsNo) {
this.goodsNo = goodsNo;
}
public String getGoodsName() {
return goodsName;
}
public void setGoodsName(String goodsName) {
this.goodsName = goodsName;
}
public String getContainerNo() {
return containerNo;
}
public void setContainerNo(String containerNo) {
this.containerNo = containerNo;
}
public String getOwnerNo() {
return ownerNo;
}
public void setOwnerNo(String ownerNo) {
this.ownerNo = ownerNo;
}
public String getCreateUser() {
return createUser;
}
public void setCreateUser(String createUser) {
this.createUser = createUser;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getUpdateUser() {
return updateUser;
}
public void setUpdateUser(String updateUser) {
this.updateUser = updateUser;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public Integer getYn() {
return yn;
}
public void setYn(Integer yn) {
this.yn = yn;
}
public String getDistributeNo() {
return distributeNo;
}
public void setDistributeNo(String distributeNo) {
this.distributeNo = distributeNo;
}
public String getOrgNo() {
return orgNo;
}
public void setOrgNo(String orgNo) {
this.orgNo = orgNo;
}
public String getWarehouseNo() {
return warehouseNo;
}
public void setWarehouseNo(String warehouseNo) {
this.warehouseNo = warehouseNo;
}
public String getSnStart() {
return snStart;
}
public void setSnStart(String snStart) {
this.snStart = snStart;
}
public String getSnEnd() {
return snEnd;
}
public void setSnEnd(String snEnd) {
this.snEnd = snEnd;
}
public String getReceivingNo() {
return receivingNo;
}
public void setReceivingNo(String receivingNo) {
this.receivingNo = receivingNo;
}
public String getFinishFlag() {
return finishFlag;
}
public void setFinishFlag(String finishFlag) {
this.finishFlag = finishFlag;
}
public String getQueryUser() {
return queryUser;
}
public void setQueryUser(String queryUser) {
this.queryUser = queryUser;
}
public String getOutWaveNo() {
return outWaveNo;
}
public void setOutWaveNo(String outWaveNo) {
this.outWaveNo = outWaveNo;
}
public List<String> getSnList() {
return snList;
}
public void setSnList(List<String> snList) {
this.snList = snList;
}
}
the result
org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.reflection.ReflectionException: There is no getter for property named '' in 'class java.lang.String'
IbSnTransit.snList is declared as List of String.class objects so, when you use #{item.sn,jdbcType=VARCHAR} in your mapper you are asked for a property sn in the String.class. Maybe you must use #{item,jdbcType=VARCHAR} instead.

Categories