this is my apicall
public void loadData(String lat,String lon){
pd = new ProgressDialog(getActivity());
pd.setMessage("Loading");
pd.show();
mApi = new RetrofitHelper<AuthApi>().getApi(AuthApi.class);
currentCall = mApi.currentData(lat,lon,units,key);
currentCall.enqueue(new Callback<ResultObject>() {
#Override
public void onResponse(Call<ResultObject> call,
Response<ResultObject> response) {
Log.d("enter","enter");
Log.d("temp",new Integer(response.body().getMain().getTemp()).toString());
temp_current.setText(new Integer(response.body().getMain().getTemp()).toString());
pd.hide();
}
#Override
public void onFailure(Call<ResultObject> call, Throwable t) {
pd.hide();
}
});
}
This logs with the keys "enter" and "temp" doesnot show up on tbe logcat that means it is not entering the OnResponse method
this is my api request inteface
#GET("weather")
Call<ResultObject> currentData(
#Query("lat") String lat,
#Query("lon") String lon,
#Query("units") String units,
#Query("APPID") String APPID
);
this is my result class(json matching),just made required fields for the "main" field in json response.
i dont know if this ResultObject class is parsing the response or not
public class ResultObject{
#Expose
#SerializedName("message")
public String message;
#Expose
#SerializedName("result")
public int result;
#Expose
#SerializedName("main")
public Main main;
public class Main {
#Expose
#SerializedName("temp")
public int temp;
#Expose
#SerializedName("pressure")
public int pressure;
#Expose
#SerializedName("humidity")
public int humidity;
#Expose
#SerializedName("temp_min")
public int temp_min;
#Expose
#SerializedName("temp_max")
public int temp_max;
public int getTemp() {
return temp;
}
public void setTemp(int temp) {
this.temp = temp;
}
public int getPressure() {
return pressure;
}
public void setPressure(int pressure) {
this.pressure = pressure;
}
public int getHumidity() {
return humidity;
}
public void setHumidity(int humidity) {
this.humidity = humidity;
}
public int getTemp_min() {
return temp_min;
}
public void setTemp_min(int result) {
this.temp_min = temp_min;
}
public int getTemp_max() {
return temp_max;
}
public void setTemp_max(int result) {
this.temp_max = temp_max;
}
}
#Expose
#SerializedName("errors")
public List<String> errors;
public List<String> getErrors() {
return errors;
}
public void setErrors(List<String> errors) {
this.errors = errors;
}
public Main getMain() {
return main;
}
public void setmain(Main main) {
this.main = main;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public int getResult() {
return result;
}
public void setResult(int result) {
this.result = result;
}
}
I logged the response,which is this
{"coord":{"lon":0,"lat":0},
"weather":[{"id":804,"main":"Clouds","description":"overcast clouds","icon":"04n"}],
"base":"stations",
"main":{"temp":25.71,"pressure":1026.51,"humidity":100,"temp_min":25.71,"temp_max":25.71,"sea_level":1026.58,"grnd_level":1026.51},
"wind":{"speed":6.41,"deg":190.004},
"clouds":{"all":92},
"dt":1497210848,
"sys":{"message":0.0084,"sunrise":1497160571,"sunset":1497204213},"id":6295630,"name":"Earth","cod":200}
I get the response but the OnResponse method does not work
I am not able resolve it, please help
Related
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;
I'm trying to get a JSON file using an URL, but the application is crashing.
JSON file api
MainActivity.java
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ApiService.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiService service = retrofit.create(ApiService.class);
// Logs show error is in the code below
service.getPopulationData(new Callback<Flag> (){
#Override
public void onResponse(Call<Flag> call, Response<Flag> response) {
Log.d("JSONData", response.body().toString());
}
#Override
public void onFailure(Call<Flag> call, Throwable t) {
Log.d("JSONData", t.getMessage());
}
});
ApiService.java
public interface ApiService {
String BASE_URL = "http://www.androidbegin.com/";
#GET("tutorial/jsonparsetutorial.txt")
public void getPopulationData(Callback<Flag> callback) ;
}
Flag.java
public class Flag {
private int rank;
private String country;
private String population;
private String flag;
public int getRank() {
return rank;
}
public void setRank(int rank) {
this.rank = rank;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getPopulation() {
return population;
}
public void setPopulation(String population) {
this.population = population;
}
public String getFlag() {
return flag;
}
public void setFlag(String flag) {
this.flag = flag;
}
}
Edit: Error log can be found here: log
I've tried other solutions mentioned on stackoverflow, but I've been unable to get it right.
Also, I only want the flag URLs from the JSON file. How am I supposed to get it?
You will need the following two pojo class
JsonResponse.java
public class JsonResponse {
#SerializedName("worldpopulation")
#Expose
private List<Worldpopulation> worldpopulation = null;
public List<Worldpopulation> getWorldpopulation() {
return worldpopulation;
}
public void setWorldpopulation(List<Worldpopulation> worldpopulation) {
this.worldpopulation = worldpopulation;
}
}
Worldpopulation.java
public class Worldpopulation {
#SerializedName("rank")
#Expose
private Integer rank;
#SerializedName("country")
#Expose
private String country;
#SerializedName("population")
#Expose
private String population;
#SerializedName("flag")
#Expose
private String flag;
public Integer getRank() {
return rank;
}
public void setRank(Integer rank) {
this.rank = rank;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getPopulation() {
return population;
}
public void setPopulation(String population) {
this.population = population;
}
public String getFlag() {
return flag;
}
public void setFlag(String flag) {
this.flag = flag;
}
}
and make a retrofit call like below
service.getPopulationData(new Callback<JsonResponse> (){
#Override
public void onResponse(Call<JsonResponse> call, Response<JsonResponse> response) {
Log.d("JSONData", response.body().toString());
ArrayList<Worldpopulation> population=new ArrayList(response.body().getWorldpopulation());
}
#Override
public void onFailure(Call<JsonResponse> call, Throwable t) {
Log.d("JSONData", t.getMessage());
}
});
**** edited as per requirement ****
and change ApiService.java
public interface ApiService {
String BASE_URL = "http://www.androidbegin.com/";
#GET("tutorial/jsonparsetutorial.txt")
Call<JsonResponse> getPopulationData() ;
}
and call it like this
made an edit here
ApiService service = retrofit.create(ApiService.class);
Call<JsonResponse> call = service.getPopulationData();
call.enqueue(new Callback<JsonResponse> (){
#Override
public void onResponse(Call<JsonResponse> call, Response<JsonResponse> response) {
Log.d("JSONData", response.body().toString());
ArrayList<Worldpopulation> population=new ArrayList(response.body().getWorldpopulation());
}
#Override
public void onFailure(Call<JsonResponse> call, Throwable t) {
Log.d("JSONData", t.getMessage());
}
});
The json you are trying to parse with Retrofit contains a JSON Array as its root worldpopulation , So First you need a class WorldPopulation as follow:
public class WorldPopulation
{
private List<Flag> worldpopulation;
public List<Flag> getWorldpopulation() {
return worldpopulation;
}
public void setWorldpopulation(List<Flag> worldpopulation) {
this.worldpopulation = worldpopulation;
}
}
public interface ApiService {
String BASE_URL = "http://www.androidbegin.com/";
#GET("tutorial/jsonparsetutorial.txt")
public void getPopulationData(Callback<WorldPopulation> callback) ;
}
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},
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();
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"