Retrofit Help, always getting responseFailed - java

I have been trying to learn implementing Retrofit since past couple of days but I have been facing some issues. COuld someone pls help?
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Retrofit.Builder builder = new Retrofit.Builder().baseUrl("https://query.yahooapis.com") .addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit = builder.build();
Details client = retrofit.create(Details.class);
Call<ArrayList<Condition>> call = client.reposForUser();
call.enqueue(new Callback<ArrayList<Condition>>() {
#Override
public void onResponse(Call<ArrayList<Condition>> call, Response<ArrayList<Condition>> response) {
Toast.makeText(MainActivity.this, "Yes", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<ArrayList<Condition>> call, Throwable t) {
Toast.makeText(MainActivity.this, "NO", Toast.LENGTH_SHORT).show();
System.out.print(t.getStackTrace().toString());
}
});
}
}
////////////////////////////////////////////////////////////////////////////
public interface Details {
#GET("/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22New%20Delhi%2CIndia%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys")
Call<ArrayList<Condition>> reposForUser();
}
///////////////////////////////////////////////////////////////////////////////
package hawkeyestudios.weatherretro;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Condition {
#SerializedName("code")
#Expose
private String code;
#SerializedName("date")
#Expose
private String date;
#SerializedName("temp")
#Expose
private String temp;
#SerializedName("text")
#Expose
private String text;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTemp() {
return temp;
}
public void setTemp(String temp) {
this.temp = temp;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}

I made call to your API,based upon those json, I have segment the object.This is your Response class which holds the entire json, if you could request for Response class, you could get your json
public class Response {
#SerializedName("query")
#Expose
private Query query;
public Query getQuery() {
return query;
}
public void setQuery(Query query) {
this.query = query;
}
}
------------The Query class which holds the Result class------
public class Query {
#SerializedName("results")
#Expose
private Results results;
public Results getResults() {
return results;
}
public void setResults(Results results) {
this.results = results;
}
}
--------The result class which holds the Channels class
public class Results {
#SerializedName("channel")
#Expose
private Channel channel;
public Channel getChannel() {
return channel;
}
public void setChannel(Channel channel) {
this.channel = channel;
}
}
---This is the Channel class which holds the Item class
public class Channel {
#SerializedName("item")
#Expose
private Item item;
public Item getItem() {
return item;
}
public void setItem(Item item) {
this.item = item;
}
}
----This is the Item class which holds your actual data Condition which is not array but single object based upon your json response ---
public class Item {
#SerializedName("condition")
#Expose
private Condition condition;
public Condition getCondition() {
return condition;
}
public void setCondition(Condition condition) {
this.condition = condition;
}
}
-----Finally the Condition class
public class Condition {
#SerializedName("code")
#Expose
private String code;
#SerializedName("date")
#Expose
private String date;
#SerializedName("temp")
#Expose
private String temp;
#SerializedName("text")
#Expose
private String text;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTemp() {
return temp;
}
public void setTemp(String temp) {
this.temp = temp;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
//So finally make some change
call<Response> call = client.reposForUser();

Related

Android Java expected begin_object but was begin_array

Please Help me
This is my Models
Cases class
public class Cases {
#SerializedName("new")////this key value from json
#Expose
private String _new;
#SerializedName("active")
#Expose
private Integer active;
#SerializedName("critical")
#Expose
private Integer critical;
#SerializedName("recovered")
#Expose
private Integer recovered;
#SerializedName("1M_pop")
#Expose
private String _1MPop;
#SerializedName("total")
#Expose
private Integer total;
public String getNew() {
return _new;
}
public void setNew(String _new) {
this._new = _new;
}
public Integer getActive() {
return active;
}
public void setActive(Integer active) {
this.active = active;
}
public Integer getCritical() {
return critical;
}
public void setCritical(Integer critical) {
this.critical = critical;
}
public Integer getRecovered() {
return recovered;
}
public void setRecovered(Integer recovered) {
this.recovered = recovered;
}
public String get1MPop() {
return _1MPop;
}
public void set1MPop(String _1MPop) {
this._1MPop = _1MPop;
}
public Integer getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
}
Deaths class
public class Deaths {
#SerializedName("new")
#Expose
private String _new;
#SerializedName("1M_pop")
#Expose
private String _1MPop;
#SerializedName("total")
#Expose
private Integer total;
public String getNew() {
return _new;
}
public void setNew(String _new) {
this._new = _new;
}
public String get1MPop() {
return _1MPop;
}
public void set1MPop(String _1MPop) {
this._1MPop = _1MPop;
}
public Integer getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
}
public class Errors {//this is empty class
}
public class Parameters {//this is empty class
}
Tests class
public class Tests {
#SerializedName("1M_pop")
#Expose
private String _1MPop;
#SerializedName("total")
#Expose
private Integer total;
public String get1MPop() {
return _1MPop;
}
public void set1MPop(String _1MPop) {
this._1MPop = _1MPop;
}
public Integer getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
}
Response class
public class Response {
#SerializedName("continent")
#Expose
private String continent;
#SerializedName("country")
#Expose
private String country;
#SerializedName("population")
#Expose
private Integer population;
#SerializedName("cases")
#Expose
private Cases cases;
#SerializedName("deaths")
#Expose
private Deaths deaths;
#SerializedName("tests")
#Expose
private Tests tests;
#SerializedName("day")
#Expose
private String day;
#SerializedName("time")
#Expose
private String time;
public String getContinent() {
return continent;
}
public String getCountry() {
return country;
}
public Integer getPopulation() {
return population;
}
public Cases getCases() {
return cases;
}
public Deaths getDeaths() {
return deaths;
}
public Tests getTests() {
return tests;
}
public String getDay() {
return day;
}
public String getTime() {
return time;
}
}
Covid19Model class
public class Covid19Model {
#SerializedName("get")
#Expose
private String get;
#SerializedName("parameters")
#Expose
private Parameters parameters;
#SerializedName("errors")
#Expose
private Errors errors;
#SerializedName("results")
#Expose
private Integer results;
#SerializedName("response")
#Expose
private List<Response> response;
public String getGet() {
return get;
}
public void setGet(String get) {
this.get = get;
}
public Parameters getParameters() {
return parameters;
}
public void setParameters(Parameters parameters) {
this.parameters = parameters;
}
public Errors getErrors() {
return errors;
}
public void setErrors(Errors errors) {
this.errors = errors;
}
public Integer getResults() {
return results;
}
public void setResults(Integer results) {
this.results = results;
}
public List<Response> getResponse() {
return response;
}
public void setResponse(List<Response> response) {
this.response = response;
}
Covid19WebAPI interface
public interface Covid19WebApi {
#Headers({
"x-rapidapi-host:covid-193.p.rapidapi.com",
"x-rapidapi-key:fb818f40c4msh9ed8e59abf0e867p11b3bfjsn0900d33b78ef"//this is my rapidapi key
})
#GET("statistics")
Call<Covid19Model> getData();
}
MainActivity class
public class MainActivity extends AppCompatActivity {//This is my app MainActivity
List<Response> responses;
private static final String BASE_URL = "https://covid-193.p.rapidapi.com/";//this is covid api website
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create());//this is convert json
Retrofit retrofit = builder.build();
Covid19WebApi covid19WebApi = retrofit.create(Covid19WebApi.class);
Call<Covid19Model> call = covid19WebApi.getData();//this is call api interfacee method
call.enqueue(new Callback<Covid19Model>() {
#Override
public void onResponse(Call<Covid19Model> call, Response<Covid19Model> response) {
responses = response.body().getResponse();
for (Object data:responses){
System.out.println(data);//This my error (expected begin_array but was begin_object )
}
}
#Override
public void onFailure(Call<Covid19Model> call, Throwable t) {
Toast.makeText(MainActivity.this,t.getLocalizedMessage().toString(),Toast.LENGTH_LONG).show();//this is toast message failure
}
});
}
}
What is the problem
My error code ("expected begin_array but was begin_object")
I can't find out what the problem is in these codes and the data doesn't come in response and gives an error instead
As you can see in JSON response, errors and parameters are comes as List.
So please change fields to list in Covid19Model
#SerializedName("parameters")
#Expose
private List<Parameters> parameters;
#SerializedName("errors")
#Expose
private List<Errors> errors;

Retrofit with Gson Response.body() not working

I'am trying to parse data to a recyclerview, i had some problems about expecting JSONArray/JSONObject that i fixed with some help, but this moment I am a little bit lost in what to do in the Onresponse, the original - generatePhonesList(response.body()) isnt working.
this is my json and i am trying to parse the data inside the array results[] :
{
"success": true,
"metadata": {
"sort": "POPULARITY",
"total_products": 20,
"title": "Phones & Tablets",
"results": [
{
"sku": "1",
"name": "Samsung Galaxy S9",
"brand": "Samsung",
"max_saving_percentage": 30,
"price": 53996,
"special_price": 37990,
"image": "https://cdn2.gsmarena.com/vv/bigpic/samsung-galaxy-s9-.jpg",
"rating_average": 5
},
MainActivity (CALL and Recyclerview creation) :
GetPhoneDataService service = RetrofitInstance.getRetrofitInstance().create(GetPhoneDataService.class);
Call<APIReponse> call = service.getAllPhones();
call.enqueue(new Callback<APIReponse>() {
#Override
public void onResponse(Call<APIReponse> call, Response<APIReponse> response) {
generatePhonesList(response.body());
}
#Override
public void onFailure(Call<APIReponse> call, Throwable t) {
Log.e("eee" , "" + t.getMessage());
}
});
}
private void generatePhonesList(List<Result> phonesList){
recyclerView = findViewById(R.id.recyclerView);
adapter = new PhonesAdapter(phonesList,this);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
}
this is the POJO Class's created in jsonschema2pojo :
public class APIReponse {
#SerializedName("success")
#Expose
private Boolean success;
#SerializedName("metadata")
#Expose
private Metadata metadata;
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public Metadata getMetadata() {
return metadata;
}
public void setMetadata(Metadata metadata) {
this.metadata = metadata;
}
}
2 class
public class MetaData {
#SerializedName("sort")
#Expose
private String sort;
#SerializedName("total_products")
#Expose
private Integer totalProducts;
#SerializedName("title")
#Expose
private String title;
#SerializedName("results")
#Expose
private List<Result> results = null;
public String getSort() {
return sort;
}
public void setSort(String sort) {
this.sort = sort;
}
public Integer getTotalProducts() {
return totalProducts;
}
public void setTotalProducts(Integer totalProducts) {
this.totalProducts = totalProducts;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<Result> getResults() {
return results;
}
public void setResults(List<Result> results) {
this.results = results;
}
}
3 class:
public class Result {
#SerializedName("sku")
#Expose
private String sku;
#SerializedName("name")
#Expose
private String name;
#SerializedName("brand")
#Expose
private String brand;
#SerializedName("max_saving_percentage")
#Expose
private Integer maxSavingPercentage;
#SerializedName("price")
#Expose
private Integer price;
#SerializedName("special_price")
#Expose
private Integer specialPrice;
#SerializedName("image")
#Expose
private String image;
#SerializedName("rating_average")
#Expose
private Integer ratingAverage;
public String getSku() {
return sku;
}
public void setSku(String sku) {
this.sku = sku;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public Integer getMaxSavingPercentage() {
return maxSavingPercentage;
}
public void setMaxSavingPercentage(Integer maxSavingPercentage) {
this.maxSavingPercentage = maxSavingPercentage;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
public Integer getSpecialPrice() {
return specialPrice;
}
public void setSpecialPrice(Integer specialPrice) {
this.specialPrice = specialPrice;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public Integer getRatingAverage() {
return ratingAverage;
}
public void setRatingAverage(Integer ratingAverage) {
this.ratingAverage = ratingAverage;
}
}
You are passing the APIReponse model to the generatePhonesList(List<Result> phonesList) function. You need to pass only the list of results in this function.
Replace this:
generatePhonesList(response.body());
with:
generatePhonesList(response.body().getMetadata().getResults());
Here getMetadata() and getResults() are the getter functions of metadata model and List.
If you pay close attention response.body() will provide you with class APIResponse. But you need is List<Result>. To achieve this, try response.body().getMetadata().getResults()
This should give you the desired output.

Json Get Request using retrofit won't work

Until this api i had this ones and my code worked now i can not figure out what i need to get and what to put in Map also i don't know where to start to get this response into my app.
This api i know how work and i have working code for it :
https://gyazo.com/f2eb4858c48c31c5c48765a9e7512179
But this one api is really hard to figure for me.
https://gyazo.com/d2bad9dbe66bf7c51b169b54a68a003a
I really don't know what i need to put here in Map and how to get "result" array(if that is array list?? )
Thank you guys this is my unworking example.
Datas.class
package Model.BittrexApiModel;
public class Datas {
private Result result;
public Result getResult() {
return result;
}
public void setResult(Result result) {
this.result = result;
}
public Datas withDatas(Result result){
this.result=result;
return this;
}
}
Here is my Result POJO CLASS
package Model.BittrexApiModel;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Result {
#SerializedName("MarketName")
#Expose
private String marketName;
#SerializedName("High")
#Expose
private Double high;
#SerializedName("Low")
#Expose
private Double low;
#SerializedName("Volume")
#Expose
private Double volume;
#SerializedName("Last")
#Expose
private Double last;
#SerializedName("BaseVolume")
#Expose
private Double baseVolume;
#SerializedName("TimeStamp")
#Expose
private String timeStamp;
#SerializedName("Bid")
#Expose
private Double bid;
#SerializedName("Ask")
#Expose
private Double ask;
#SerializedName("OpenBuyOrders")
#Expose
private Integer openBuyOrders;
#SerializedName("OpenSellOrders")
#Expose
private Integer openSellOrders;
#SerializedName("PrevDay")
#Expose
private Double prevDay;
#SerializedName("Created")
#Expose
private String created;
public String getMarketName() {
return marketName;
}
public void setMarketName(String marketName) {
this.marketName = marketName;
}
public Result withMarketName(String marketName) {
this.marketName = marketName;
return this;
}
public Double getHigh() {
return high;
}
public void setHigh(Double high) {
this.high = high;
}
public Result withHigh(Double high) {
this.high = high;
return this;
}
public Double getLow() {
return low;
}
public void setLow(Double low) {
this.low = low;
}
public Result withLow(Double low) {
this.low = low;
return this;
}
public Double getVolume() {
return volume;
}
public void setVolume(Double volume) {
this.volume = volume;
}
public Result withVolume(Double volume) {
this.volume = volume;
return this;
}
public Double getLast() {
return last;
}
public void setLast(Double last) {
this.last = last;
}
public Result withLast(Double last) {
this.last = last;
return this;
}
public Double getBaseVolume() {
return baseVolume;
}
public void setBaseVolume(Double baseVolume) {
this.baseVolume = baseVolume;
}
public Result withBaseVolume(Double baseVolume) {
this.baseVolume = baseVolume;
return this;
}
public String getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(String timeStamp) {
this.timeStamp = timeStamp;
}
public Result withTimeStamp(String timeStamp) {
this.timeStamp = timeStamp;
return this;
}
public Double getBid() {
return bid;
}
public void setBid(Double bid) {
this.bid = bid;
}
public Result withBid(Double bid) {
this.bid = bid;
return this;
}
public Double getAsk() {
return ask;
}
public void setAsk(Double ask) {
this.ask = ask;
}
public Result withAsk(Double ask) {
this.ask = ask;
return this;
}
public Integer getOpenBuyOrders() {
return openBuyOrders;
}
public void setOpenBuyOrders(Integer openBuyOrders) {
this.openBuyOrders = openBuyOrders;
}
public Result withOpenBuyOrders(Integer openBuyOrders) {
this.openBuyOrders = openBuyOrders;
return this;
}
public Integer getOpenSellOrders() {
return openSellOrders;
}
public void setOpenSellOrders(Integer openSellOrders) {
this.openSellOrders = openSellOrders;
}
public Result withOpenSellOrders(Integer openSellOrders) {
this.openSellOrders = openSellOrders;
return this;
}
public Double getPrevDay() {
return prevDay;
}
public void setPrevDay(Double prevDay) {
this.prevDay = prevDay;
}
public Result withPrevDay(Double prevDay) {
this.prevDay = prevDay;
return this;
}
public String getCreated() {
return created;
}
public void setCreated(String created) {
this.created = created;
}
public Result withCreated(String created) {
this.created = created;
return this;
}
}
And here is my BittrexResponse.class ( i think this one is not working.)
package Model.BittrexApiModel;
import java.util.Map;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class BittrexResponse {
#SerializedName("success")
#Expose
private Boolean success;
#SerializedName("message")
#Expose
private String message;
#SerializedName("result")
#Expose
private Map<String, Result> datas;
public Map<String,Result> getDatas(){
return datas;
}
public void setDatas(Map<String,Result> datas){
this.datas=datas;
}
//private List<Result> result = new ArrayList<>();
//This is first original JSONSCHEMA2POJO - SAVING RESPONSE DON't WORK
// private List<Result> result = new ArrayList<Result>();
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public BittrexResponse withSuccess(Boolean success) {
this.success = success;
return this;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public BittrexResponse withMessage(String message) {
this.message = message;
return this;
}
ApiClient.class (working , tested on earlier examples)
package Model.CoinMarketCapApiModel;
import com.test.retrofit.CryptoCyber.Settings;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class ApiClient {
public static final String BASE_URL = Settings.getBase_url();
private static Retrofit retrofit = null;
public static Retrofit getClient() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
retrofit = new Retrofit.Builder()
.client(client)
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit;
}
}
I hope someone will help me to figure out why i don't know get data and save it to map...
P.s. here is link for api
CLICK HERE
Here's a possible way to design your classes to correctly parse the response.
ApiResponse
public class ApiResponse {
private boolean success;
private String message;
#SerializedName("result")
private List<Market> markets;
// Other fields + getters&setters
...
}
Market
public class Market {
#SerializedName("MarketName")
private String marketName;
#SerializedName("High")
private double high;
#SerializedName("Low")
private double low;
#SerializedName("Volume")
private double volume;
// Other fields + getters&setters
...
}
Main
public class Main {
public static void main(String[] args) throws IOException {
Retrofit retrofit = createRetrofit();
Api api = retrofit.create(Api.class);
retrofit2.Response<ApiResponse> response = api.getMarketSummaries().execute();
if (!response.isSuccessful()) {
// Handle error case
} else {
ApiResponse marketApiResponse = response.body();
System.out.println(marketApiResponse);
}
}
private static Retrofit createRetrofit() {
return new Retrofit.Builder()
.baseUrl("https://bittrex.com/api/v1.1/public/")
.addConverterFactory(GsonConverterFactory.create())
.build();
}
}
It will print something like this (only first item of the list is reported for the sake of brevity):
ApiResponse{success=true, message='', markets=[Market{marketName='BTC-2GIVE', high=1.1E-6, low=9.7E-7, volume=3499023.70109898},

How to parse JSON using GSON?

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.

null values returning from gson.fromJson

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"

Categories

Resources