How get value in array "rate" to invoke getters methods ?
My Json response is something as below and confused how to parse it using GSON. Please have look on the following and guide me how i can parse it using GSON.
data.json
{
"query":{
"count":2,
"created":"2017-01-03T12:45:19Z",
"lang":"en-us",
"results":{
"rate":[
{
"id":"BTC/USD",
"Name":"BTCUSD",
"Rate":"985.50",
"Date":"1/3/2017",
"Time":"10:35am",
"Ask":"985.50",
"Bid":"985.35"
},
{
"id":"BTC/EUR",
"Name":"BTCEUR",
"Rate":"973.16",
"Date":"1/3/2017",
"Time":"10:35am",
"Ask":"973.16",
"Bid":"973.10"
}
]
}
}
}
I use classes to parse apart
Market.java
public class Market {
#SerializedName("query")
private Query query;
public Query getQuery() {
return query;
}
public void setQuery(Query query) {
this.query = query;
}
}
Query.java
public class Query {
#SerializedName("count")
private Integer count;
#SerializedName("created")
private String created;
#SerializedName("lang")
private String lang;
#SerializedName("results")
private Results results;
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
public String getCreated() {
return created;
}
public void setCreated(String created) {
this.created = created;
}
public String getLang() {
return lang;
}
public void setLang(String lang) {
this.lang = lang;
}
public Results getResults() {
return results;
}
public void setResults(Results results) {
this.results = results;
}
}
Rate.java
public class Rate {
#SerializedName("id")
private String id;
#SerializedName("Name")
private String name;
#SerializedName("Rate")
private String rate;
#SerializedName("Date")
private String date;
#SerializedName("Time")
private String time;
#SerializedName("Ask")
private String ask;
#SerializedName("Bid")
private String bid;
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 String getRate() {
return rate;
}
public void setRate(String rate) {
this.rate = rate;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getAsk() {
return ask;
}
public void setAsk(String ask) {
this.ask = ask;
}
public String getBid() {
return bid;
}
public void setBid(String bid) {
this.bid = bid;
}
}
Results.java
public class Results {
#SerializedName("rate")
private List<Rate> rate = null;
public List<Rate> getRate() {
return rate;
}
public void setRate(List<Rate> rate) {
this.rate = rate;
}
}
Trying to get the values
Main.java
public class Main {
/* ..... */
Gson gson = new Gson();
Market market = gson.fromJson(json, Market.class);
//error: incompatible types: Rate cannot be converted to List<Rate>
for( List<Rate> res : market.getQuery().getResults().getRate());
{
Log.v(LOG_TAG, res); // error: cannot find symbol variable res
}
}
how to do it properly ?
The syntax of your for each loop is incorrect. Since you are attempting to loop through a list of Rate objects, the type of res should be a Rate, not a list of Rates:
for (Rate res : market.getQuery().getResults().getRate()) {
// code here
}
As an aside, you should consider checking for null values before dereferencing all of those child objects as you run the risk of throwing a NullPointerException at runtime.
Related
I have query:
public List<InvoiceItems> findAllBalance(String external_key) throws HibernateException {
return (List<InvoiceItems>) session.createQuery("select SUM(i.amount) as amount, t.record_id from Accounts a, InvoiceItems i, Tenant t WHERE a.record_id = i.account_record_id AND t.record_id=a.tenant_record_id AND a.external_key='"+external_key+"' group by i.tenant_record_id, t.record_id").list();
}
InvoiceItems.java:
package id.co.keriss.consolidate.ee;
import java.util.Date;
import org.jpos.ee.Accounts;
public class InvoiceItems {
private long record_id;
private String id;
private String type;
private String invoice_id;
private Accounts account_record_id;
private Tenant tenant_record_id;
private String description;
private long amount;
private Date created_date;
private String usage_name;
private String plan_name;
private String account_id;
public String getAccount_id() {
return account_id;
}
public void setAccount_id(String account_id) {
this.account_id = account_id;
}
public long getRecord_id() {
return record_id;
}
public void setRecord_id(long record_id) {
this.record_id = record_id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getInvoice_id() {
return invoice_id;
}
public void setInvoice_id(String invoice_id) {
this.invoice_id = invoice_id;
}
public Accounts getAccount_record_id() {
return account_record_id;
}
public void setAccount_record_id(Accounts account_record_id) {
this.account_record_id = account_record_id;
}
public Tenant getTenant_record_id() {
return tenant_record_id;
}
public void setTenant_record_id(Tenant tenant_record_id) {
this.tenant_record_id = tenant_record_id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public long getAmount() {
return amount;
}
public void setAmount(long amount) {
this.amount = amount;
}
public Date getCreated_date() {
return created_date;
}
public void setCreated_date(Date created_date) {
this.created_date = created_date;
}
public String getUsage_name() {
return usage_name;
}
public void setUsage_name(String usage_name) {
this.usage_name = usage_name;
}
public String getPlan_name() {
return plan_name;
}
public void setPlan_name(String plan_name) {
this.plan_name = plan_name;
}
}
then set to an variable:
List<InvoiceItems> invoiceItems = invoiceItemsDao.findAllBalance(jsonRecv.getString("externalkey"));
I want to get the value from that query, what I try:
LogSystem.info(request, "List : " + invoiceItems.get(0).getId();
I got an error "can't cast to InvoiceItems"
then I try changing from List<InvoiceItems> to just List
get with this :
LogSystem.info(request, "List : " + invoiceItems.get(0);
but the output like this not the value:
[Ljava.lang.Object;#41ea9df8
any advice? final result what i want is calculate amount of tenant
session.createQuery take HQL (Hibernate query language) however I see you use native SQL. Try using createSQLQuery method.
public List<InvoiceItems> findAllBalance(String external_key) throws HibernateException {
Query query = session.createSQLQuery("select SUM(i.amount) as amount, t.record_id from Accounts a, InvoiceItems i, Tenant t WHERE a.record_id = i.account_record_id AND t.record_id=a.tenant_record_id AND a.external_key='"+external_key+"' group by i.tenant_record_id, t.record_id");
query.setResultTransformer(Transformers.aliasToBean(InvoiceItems.class));
List<InvoiceItems> list = query.list();
return list;
}
i have this function to query in hibernate:
public List<TransactionQR> getAllTransaction() throws HibernateException {
return this.session.createQuery("SELECT id FROM TransactionQR").list();
}
then is success to show the data like this in html:
[2, 3]
but when i add more column in SELECT like this:
public List<TransactionQR> getAllTransaction() throws HibernateException {
return this.session.createQuery("SELECT id, codeqr FROM TransactionQR").list();
}
the result show like this:
[Ljava.lang.Object;#25026824, [Ljava.lang.Object;#170b75f9]
what is Ljava.lang.Object;#25026824 ? is return object, can i handle it to convert from list to json ?
i have model TransactionQR.java :
public class TransactionQR implements Serializable {
private Long id;
private String codeqr;
private Date approvaltime;
private String merchant;
private String code_merchant;
private Long amount;
private Long saldoawal;
private Integer tracenumber;
private String state;
private Date createdate;
private Batch batch;
public TransactionQR() {
}
public TransactionQR(Long id, String codeqr, Date approvaltime, String merchant, String code_merchant, Long amount,
Long saldoawal, Integer tracenumber, String state, Date createdate, Batch batch) {
super();
this.id = id;
this.codeqr = codeqr;
this.approvaltime = approvaltime;
this.merchant = merchant;
this.code_merchant = code_merchant;
this.amount = amount;
this.saldoawal = saldoawal;
this.tracenumber = tracenumber;
this.state = state;
this.createdate = createdate;
this.batch = batch;
}
public Long getId() {
return id;
}
public Date getApprovalTime() {
return approvaltime;
}
public Batch getBatch() {
return batch;
}
public void setBatch(Batch batch) {
this.batch = batch;
}
public void setApprovalTime(Date approvalTime) {
this.approvaltime = approvalTime;
}
public void setId(Long id) {
this.id = id;
}
public Date getApprovaltime() {
return approvaltime;
}
public void setApprovaltime(Date approvaltime) {
this.approvaltime = approvaltime;
}
public String getCodeqr() {
return codeqr;
}
public void setCodeqr(String codeqr) {
this.codeqr = codeqr;
}
public String getMerchant() {
return merchant;
}
public void setMerchant(String merchant) {
this.merchant = merchant;
}
public String getCode_merchant() {
return code_merchant;
}
public void setCode_merchant(String code_merchant) {
this.code_merchant = code_merchant;
}
public Long getAmount() {
return amount;
}
public void setAmount(Long amount) {
this.amount = amount;
}
public Long getSaldoawal() {
return saldoawal;
}
public void setSaldoawal(Long saldoawal) {
this.saldoawal = saldoawal;
}
public Integer getTracenumber() {
return tracenumber;
}
public void setTracenumber(Integer tracenumber) {
this.tracenumber = tracenumber;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public Date getCreatedate() {
return createdate;
}
public void setCreatedate(Date createdate) {
this.createdate = createdate;
}
}
the result is i want to show all data from database in list
In second case, since you are selecting two attributes, that is why session.createQuery("").list returns a list of object array(List<Object[]>) . At each index of list you will find an object array. Each array will have two indexes. First index will provide id while the second one would provide codeqr. So, basically you need to iterate over the list. Then fetch each value individually like arr[0], arr[1]..
The result variable contains corrected parsed JSON.
But after deserialization List contains correct amount of items but all of them are empty.
How to fix it?
Gson gson = new Gson();
List<UnitView> unitViews = new ArrayList<UnitView>();
// https://stackoverflow.com/questions/5554217/google-gson-deserialize-listclass-object-generic-type
Type typeToken = new TypeToken<List<UnitView>>() { }.getType();
unitViews = gson.fromJson(result,typeToken);
Even if I do like
UnitView[] unitViews = gson.fromJson(result, UnitView[].class);
The fields of items are empty as well.
UnitView
public class UnitView implements Serializable {
public String id ;
public String name ;
public String description ;
public String deviceTypeName ;
public String categoryID ;
public String lastOnline ;
public String latitude ;
public String longitude ;
public String atTime ;
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public String getDeviceTypeName() {
return deviceTypeName;
}
public String getCategoryID() {
return categoryID;
}
public String getLastOnline() {
return lastOnline;
}
public String getLatitude() {
return latitude;
}
public String getLongitude() {
return longitude;
}
public String getAtTime() {
return atTime;
}
public void setId(String id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setDescription(String description) {
this.description = description;
}
public void setDeviceTypeName(String deviceTypeName) {
this.deviceTypeName = deviceTypeName;
}
public void setCategoryID(String categoryID) {
this.categoryID = categoryID;
}
public void setLastOnline(String lastOnline) {
this.lastOnline = lastOnline;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public void setAtTime(String atTime) {
this.atTime = atTime;
}
}
JSON DATA
[{"ID":"294","Name":"Foton Tunland № F110","Description":null,"DeviceTypeName":"Техника ТО","CategoryID":"18","LastOnline":"19.12.2017 20:38:04","Latitude":"11,40119","Longitude":"11,42403","AtTime":"19.12.2017 20:38:04"},{"ID":"295","Name":"DML LP1200 № 9793","Description":null,"DeviceTypeName":"Буровой станок дизельный","CategoryID":"15","LastOnline":null,"Latitude":null,"Longitude":null,"AtTime":null}]
Ok , the problem is that the parser is case-sensitive, you can change the name of your attributes to match the name of the json value of you could use the SerializedName annotation like this:
#SerializedName("ID")
public String id ;
#SerializedName("Name")
public String name ;
#SerializedName("Description")
public String description;
...
or
public String ID ;
public String Name ;
public String Description ;
...
I think you're having this problem because of null values in your json.
Check it. Source
I am getting data from gemfire
List<String> objects = restTemplate.getForObject(geodeURL+"/gemfire-api/v1/queries/adhoc?q=SELECT * FROM /region s",List.class);
which is like below:
[('price':'119','volume':'20000','pe':'0','eps':'4.22','week53low':'92','week53high':'134.4','daylow':'117.2','dayhigh':'119.2','movingav50day':'115','marketcap':'0','time':'2015-11-25 05:13:34.996'), ('price':'112','volume':'20000','pe':'0','eps':'9.22','week53low':'92','week53high':'134.4','daylow':'117.2','dayhigh':'119.2','movingav50day':'115','marketcap':'0','time':'2015-11-25 05:13:34.996'), ('price':'118','volume':'20000','pe':'0','eps':'1.22','week53low':'92','week53high':'134.4','daylow':'117.2','dayhigh':'119.2','movingav50day':'115','marketcap':'0','time':'2015-11-25 05:13:34.996')]
This is a list of String I am getting.Currently I have 3 values in list.
I have a pojo class like below:
public class StockInfo {
// #Id
#JsonProperty("symbol")
private String symbol;
#JsonProperty("price")
private String price;
#JsonProperty("volume")
private String volume;
#JsonProperty("pe")
private String pe;
#JsonProperty("eps")
private String eps;
#JsonProperty("week53low")
private String week53low;
#JsonProperty("week53high")
private String week53high;
#JsonProperty("daylow")
private String daylow;
#JsonProperty("dayhigh")
private String dayhigh;
#JsonProperty("movingav50day")
private String movingav50day;
#JsonProperty("marketcap")
private String marketcap;
#JsonProperty("time")
private String time;
private String getSymbol() {
return symbol;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getVolume() {
return volume;
}
public void setVolume(String volume) {
this.volume = volume;
}
public String getPe() {
return pe;
}
public void setPe(String pe) {
this.pe = pe;
}
public String getEps() {
return eps;
}
public void setEps(String eps) {
this.eps = eps;
}
public String getWeek53low() {
return week53low;
}
public void setWeek53low(String week53low) {
this.week53low = week53low;
}
public String getWeek53high() {
return week53high;
}
public void setWeek53high(String week53high) {
this.week53high = week53high;
}
public String getDaylow() {
return daylow;
}
public void setDaylow(String daylow) {
this.daylow = daylow;
}
public String getDayhigh() {
return dayhigh;
}
public void setDayhigh(String dayhigh) {
this.dayhigh = dayhigh;
}
public String getMovingav50day() {
return movingav50day;
}
public void setMovingav50day(String movingav50day) {
this.movingav50day = movingav50day;
}
public String getMarketcap() {
return marketcap;
}
public void setMarketcap(String marketcap) {
this.marketcap = marketcap;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
How do I create a List of StockInfo class object from the value I am getting from restTemplate.getForObject
I think you could just use:
List<StockInfo> objects = restTemplate.getForObject(geodeURL+"/gemfire-api/v1/queries/adhoc?q=SELECT * FROM /region s",List.class);
I have some values in my object are returning by value null when converting from json to object and some others doesn't,i can't figure out why is that happening
here's my code to convert
OriginalMovie originalMovie = gson.fromJson(jsonString, OriginalMovie.class);
here's my json
{"page":1,
"results":[{"adult":false,
"backdrop_path":"/o4I5sHdjzs29hBWzHtS2MKD3JsM.jpg",
"genre_ids":[878,28,53,12],
"id":87101,"original_language":"en",
"original_title":"Terminator Genisys",
"overview":"The year is 2029. John Connor, leader of the resistance continues the war against the machines.",
"release_date":"2015-07-01",
"poster_path":"/5JU9ytZJyR3zmClGmVm9q4Geqbd.jpg",
"popularity":54.970301,
"title":"Terminator Genisys","video":false,
"vote_average":6.4,
"vote_count":197}],
"total_pages":11666,"total_results":233312}
and here's my base class (contains results)
package MovieReviewHelper;
import java.util.ArrayList;
import java.util.List;
public class OriginalMovie
{
private long page;
private List<Result> results = new ArrayList<Result>();
private long totalPages;
private long totalResults;
public long getPage()
{
return page;
}
public void setPage(long page)
{
this.page = page;
}
public List<Result> getResults()
{
return results;
}
public void setResults(List<Result> results)
{
this.results = results;
}
public long getTotalPages() {
return totalPages;
}
public void setTotalPages(long totalPages)
{
this.totalPages = totalPages;
}
public long getTotalResults()
{
return totalResults;
}
public void setTotalResults(long totalResults)
{
this.totalResults = totalResults;
}
}
and here's my other class
package MovieReviewHelper;
import java.util.ArrayList;
import java.util.List;
public class Result {
private boolean adult;
private String backdropPath;
private List<Long> genreIds = new ArrayList<Long>();
private long id;
private String originalLanguage;
private String originalTitle;
private String overview;
private String releaseDate;
private String posterPath;
private double popularity;
private String title;
private boolean video;
private double voteAverage;
private long voteCount;
public boolean isAdult()
{
return adult;
}
public void setAdult(boolean adult)
{
this.adult = adult;
}
public String getBackdropPath()
{
return backdropPath;
}
public void setBackdropPath(String backdropPath)
{
this.backdropPath = backdropPath;
}
public List<Long> getGenreIds()
{
return genreIds;
}
public void setGenreIds(List<Long> genreIds)
{
this.genreIds = genreIds;
}
public long getId()
{
return id;
}
public void setId(long id)
{
this.id = id;
}
public String getOriginalLanguage()
{
return originalLanguage;
}
public void setOriginalLanguage(String originalLanguage)
{
this.originalLanguage = originalLanguage;
}
public String getOriginalTitle()
{
return originalTitle;
}
public void setOriginalTitle(String originalTitle)
{
this.originalTitle = originalTitle;
}
public String getOverview()
{
return overview;
}
public void setOverview(String overview)
{
this.overview = overview;
}
public String getReleaseDate()
{
return releaseDate;
}
public void setReleaseDate(String releaseDate)
{
this.releaseDate = releaseDate;
}
public String getPosterPath()
{
return posterPath;
}
public void setPosterPath(String posterPath)
{
this.posterPath = posterPath;
}
public double getPopularity()
{
return popularity;
}
public void setPopularity(double popularity)
{
this.popularity = popularity;
}
public String getTitle()
{
return title;
}
public void setTitle(String title)
{
this.title = title;
}
public boolean isVideo()
{
return video;
}
public void setVideo(boolean video)
{
this.video = video;
}
public double getVoteAverage()
{
return voteAverage;
}
public void setVoteAverage(double voteAverage)
{
this.voteAverage = voteAverage;
}
public long getVoteCount()
{
return voteCount;
}
public void setVoteCount(long voteCount)
{
this.voteCount = voteCount;
}
}
Your Json and Class variables should have the same name.
backdrop_path in Json and backdropPath in class would not work
Incase this helps for someone like me who spent half a day in trying to figure out a similar issue with gson.fromJson() returning object with null values, but when using #JsonProperty with an underscore in name and using Lombok in the model class.
My model class had a property like below and am using Lombok #Data for class
#JsonProperty(value="dsv_id")
private String dsvId;
So in my Json file I was using
"dsv_id"="123456"
Which was causing null value. The way I resolved it was changing the Json to have below ie.without the underscore. That fixed the problem for me.
"dsvId = "123456"