How to configure project for this exact Json? - java

I have an issue with Json
when i use Gson everything is working properly, but when i use retrofit2 something is going wrong.
Class structure is exact same between retrofit and gson. difference is one additional interface and retrofit codes which is working in different cases
i uploaded every piece of code here.
String json2 = "{\"busList\":{\"bus\":[{\"forward\":\"true\",\"lat\": \"41.718979\",\"lon\": \"44.770645\",\"nextStopId\": \"1858\",\"routeNumber\": \"42\"},{\"forward\": \"true\",\"lat\": \"41.71735\",\"lon\": \"44.777855\",\"nextStopId\": \"924\",\"routeNumber\": \"42\" }]}}";
//project structure
//Class1
public class FatherBusList {
#SerializedName("busList")
private BusList busList;
public FatherBusList(BusList busList){
this.busList = busList;
}
public BusList getBusList() {
return busList;
}
}
//Class2
public class BusList {
#SerializedName("bus")
private List<Bus> buses;
public BusList (List<Bus> busses){
this.buses = busses;
}
public List<Bus> getBuses() {
return buses;
}
}
//Class3
public class Bus {
private String forward;
private String lat;
private String lon;
private String nextStopId;
private String routeNumber;
public Bus(String forward, String lat, String lon, String nextStopId, String routeNumber) {
this.forward = forward;
this.lat = lat;
this.lon = lon;
this.nextStopId = nextStopId;
this.routeNumber = routeNumber;
}
public String getForward() {
return forward;
}
public String getLat() {
return lat;
}
public String getLon() {
return lon;
}
public String getNextStopId() {
return nextStopId;
}
public String getRouteNumber() {
return routeNumber;
}
}
//retrofit2 code
//Interface for request
public interface TtcApi {
#GET("buses?routeNumber=37&forward=1&_dc=1556996108032")
Call<FatherBusList> getBus();
}
//MainActivivty
public class MainActivity extends AppCompatActivity {
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://transit.ttc.com.ge/pts-portal-services/")
.addConverterFactory(GsonConverterFactory.create())
.build();
TtcApi ttcApi = retrofit.create(TtcApi.class);
Call<FatherBusList> call = ttcApi.getBus();
call.enqueue(new Callback<FatherBusList>() {
#Override
public void onResponse(Call<FatherBusList> call, Response<FatherBusList> response) {
if (!response.isSuccessful()) {
textView.setText("Code: " + response.code());
return;
}
Toast.makeText(MainActivity.this, "Successful", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<FatherBusList> call, Throwable t) {
textView.setText(t.getMessage());
}
});
}
}
I expect to busList have 1 object and this object have arrayList
But its output is null.

{
"bus": [
{
"forward": "true",
"lat": "41.690926",
"lon": "44.816879",
"nextStopId": "1012",
"routeNumber": "37"
}
]
}
I request for your interface, return it.
Your need direct use 'BusList' class entity,don't use 'FatherBusList'

Related

How to retrieve data using retofit in Android Studio

https://pro-api.coinmarketcap.com/v1/tools/price-conversion?symbol=NGN&amount=1000897.01&convert=BTC&CMC_PRO_API_KEY=*********************************
That's the url and here is the json returned from querying that url:
{"status":{"timestamp":"2021-04-20T08:48:16.990Z","error_code":0,"error_message":null,"elapsed":17,"credit_count":1,"notice":null},"data":{"id":2819,"symbol":"NGN","name":"Nigerian Naira","amount":1000897.01,"last_updated":"2021-04-20T08:48:07.000Z","quote":{"BTC":{"price":0.0444454708294559,"last_updated":"2021-04-20T08:48:02.000Z"}}}}
the following is my code in android studio to get data from the above api en point
My pojo classes:
import com.google.gson.annotations.SerializedName;
public class CurrencyModel {
#SerializedName("name")
private String currencyName;
#SerializedName("Amount")
private int currencyAmount;
#SerializedName("quote")
Quota quota;
public CurrencyModel(Quota quota) {
this.quota = quota;
// quota.bitcoinModel.getCoinPrice();
}
public CurrencyModel(String currencyName, int currencyAmount, Quota quota) {
this.currencyName = currencyName;
this.currencyAmount = currencyAmount;
this.quota = quota;
}
public String getCurrencyName() {
return currencyName;
}
public void setCurrencyName(String currencyName) {
this.currencyName = currencyName;
}
public int getCurrencyAmount() {
return currencyAmount;
}
public void setCurrencyAmount(int currencyAmount) {
this.currencyAmount = currencyAmount;
}
public Quota getQuota() {
return quota;
}
public void setQuota(Quota quota) {
this .quota = quota;
}
public class Quota {
int price;
#SerializedName("BTC")
BitcoinModel bitcoinModel;
public Quota(BitcoinModel bitcoinModel) {
this.bitcoinModel = bitcoinModel;
}
public BitcoinModel getBitcoinModel() {
return bitcoinModel = new BitcoinModel(price);
}
public void setBitcoinModel(BitcoinModel bitcoinModel) {
this.bitcoinModel = bitcoinModel;
}
}
public class BitcoinModel {
#SerializedName("price")
private int coinPrice;
public BitcoinModel(int coinPrice) {
this.coinPrice = coinPrice;
}
public int getCoinPrice() {
return coinPrice;
}
public void setCoinPrice(int coinPrice) {
this.coinPrice = coinPrice;
}
}
My activity
public class BitcoinConversionActivity extends AppCompatActivity {
TextInputEditText amountConverted;
Button conversionButton, buyCoinButton;
TextView amountInCurrency;
int amount;
String amountEntered;
Quota quota;
CurrencyModel currencyModel;
JsonPojo pojo;
String symbol = "NGN";
String convert = "BTC";
int amountneeded = 1024587;
String apiKey = "b34416c7-2bb9-44b1-aa76-1293edd14dda";
String currencyName;
int amountnm;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_coinconversion);
amountConverted = findViewById(R.id.amount_edit_text);
amountInCurrency = findViewById(R.id.conversion_rate_tv);
conversionButton = findViewById(R.id.conversion_button);
buyCoinButton = findViewById(R.id.buy_exchange_coin_button);
conversionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
amount = Integer.parseInt(amountConverted.getText().toString());
if (TextUtils.isEmpty(Double.toString(amount))){
Toast.makeText(BitcoinConversionActivity.this, "Please Enter a valid Amount", Toast.LENGTH_LONG).show();
}else{
CoinExchange();
}
}
});
}
private void CoinExchange() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://pro-api.coinmarketcap.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
BitcoinInterface service = retrofit.create(BitcoinInterface.class);
Call<CurrencyModel> call = service.loadNairaToBitcionExchange(symbol,amountneeded,convert,apiKey);
call.enqueue(new Callback<CurrencyModel>() {
#Override
public void onResponse(Call<CurrencyModel> call, Response<CurrencyModel> response) {
if (response.isSuccessful()){
String price = response.body().toString();
//amountInCurrency.setText(price);
amountInCurrency.setText("https://pro-api.coinmarketcap.com/"+symbol+amount+convert+apiKey);
Toast.makeText(BitcoinConversionActivity.this, "Data: " + response.body().getQuota().getBitcoinModel().getCoinPrice(), Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(Call<CurrencyModel> call, Throwable t) {
Toast.makeText(BitcoinConversionActivity.this, "Error: " + t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
API interface:
public interface BitcoinInterface {
#GET("v1/tools/price-conversion?")
Call<CurrencyModel> loadNairaToBitcionExchange(#Query("symbol") String coinsSymbol,
#Query("amount") int currencyaAmount,
#Query("convert") String convertedToCurrency,
#Query("CMC_PRO_API_KEY") String ApiKey);
}
The call is returning null and at times zero.
From the API you are not getting exactly the CurrencyModel as response. You are getting another object which is CurrencyModel is a child object.
You have to create resposne object like below:
public class ResponseObject{
//#SerializedName("status")
//private int status;
#SerializedName("data")
private CurrencyModel currencyModel;
//getters and setters goes here
}
And then your interface should be like below as you are expecting ResponseObject here
public interface BitcoinInterface {
#GET("v1/tools/price-conversion?")
Call<ResponseObject> loadNairaToBitcionExchange(#Query("symbol") String coinsSymbol,
#Query("amount") int currencyaAmount,
#Query("convert") String convertedToCurrency,
#Query("CMC_PRO_API_KEY") String ApiKey);
}

App doesn't get all data from retrofit api

I finished turial from https://www.simplifiedcoding.net/retrofit-android-example/
And I wanted to create my own call, I wanted to get from API newest currency exchange, but I've got a problem (i think so this is it) with my model class. I've changed a bit code, and I've received data as "base" and "date", but whenewer I trying to get some currency value (let's take an BGN for example) program shows me always 0.0. How I may fix it? I right about that model class? Is there a problem?
Model
public class Model {
private String base,date;
private double BGN;
public Model(String base, String date, double BGN) {
this.base = base;
this.date = date;
this.BGN = BGN;
}
public String getBase() {
return base;
}
public String getDate() {
return date;
}
public double getBGN() {
return BGN;
}
}
Api (interface)
public interface Api {
String BASE_URL = "https://api.exchangeratesapi.io/";
#GET("latest")
Call<Model> getCurrency();
}
MainActivity
public class MainActivity extends AppCompatActivity {
private TextView textViewResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textViewResult = (TextView) findViewById(R.id.label);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Api.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
Api api = retrofit.create(Api.class);
Call<Model> call = api.getCurrency();
call.enqueue(new Callback<Model>() {
#Override
public void onResponse(Call<Model> call, Response<Model> response) {
List<Model> currencyList = Collections.singletonList(response.body());
for (Model currency : currencyList) {
String content = "";
content += "Base: " + currency.getBase() + "\n";
content += "Date: " + currency.getDate() + "\n";
content += "BGN: " + currency.getBGN() + "\n";
textViewResult.append(content);
}
}
#Override
public void onFailure(Call<Model> call, Throwable t) {
Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}
Api, that I trying to use https://exchangeratesapi.io/
To get all the data from retrofit, you need two POJO classes. They need to be like this where you add methods and variables for all the rates you need:
public class Model {
private String base;
private String date;
Rates RatesObject;
// Getter Methods
public String getBase() {
return base;
}
public String getDate() {
return date;
}
public Rates getRates() {
return RatesObject;
}
// Setter Methods
public void setBase(String base) {
this.base = base;
}
public void setDate(String date) {
this.date = date;
}
public void setRates(Rates ratesObject) {
this.RatesObject = ratesObject;
}
}
public class Rates {
private float CAD;
private float CHF;
private float GBP;
private float SEK;
private float EUR;
private float USD;
// Getter Methods
public float getCAD() {
return CAD;
}
public float getCHF() {
return CHF;
}
public float getGBP() {
return GBP;
}
public float getSEK() {
return SEK;
}
public float getEUR() {
return EUR;
}
public float getUSD() {
return USD;
}
// Setter Methods
public void setCAD(float CAD) {
this.CAD = CAD;
}
public void setCHF(float CHF) {
this.CHF = CHF;
}
public void setGBP(float GBP) {
this.GBP = GBP;
}
public void setSEK(float SEK) {
this.SEK = SEK;
}
public void setEUR(float EUR) {
this.EUR = EUR;
}
public void setUSD(float USD) {
this.USD = USD;
}
}

How to make parse object to json using retrofit [duplicate]

This question already has answers here:
Why does Gson fromJson throw a JsonSyntaxException: Expected BEGIN_OBJECT but was BEGIN_ARRAY?
(2 answers)
Closed 5 years ago.
with the next problem, when trying to consume a webservice, then message and presentation;
Expected BEGIN_ARRAY but was BEGIN_OBJECT
I'm not sure how to make a scenario, I've already got data from a webservice, but when it's not a simple array.
I have tried many alternatives, but without success.
response api
{
"_links": {
"self": {
"href": "http://url.com/service?page=1"
},
"first": {
"href": "http://url.com/service"
},
"last": {
"href": "http://url.com/service?page=1"
}
},
"_embedded": {
"data": [
{
"id": 1,
"nome": "teste",
"_links": {
"self": {
"href": "http://url.com/service/1"
}
}
},
{
"id": 2,
"nome": "teste 2",
"_links": {
"self": {
"href": "http://url.com/service/2"
}
}
}
]
},
"page_count": 1,
"page_size": 25,
"total_items": 2,
"page": 1
}
Client
public class ApiClient {
private static final String BASE_URL = "http://url.com/";
private static Retrofit getClient() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
Gson gson = new GsonBuilder().setLenient().create();
return new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
}
/**
* Get API Service
*
* #return API Service
*/
public static ApiInterface getApiService() {
return getClient().create(ApiInterface.class);
}
}
Interface
/**
* Class ApiInterface
*/
public interface ApiInterface
{
#Headers("Accept: application/json")
#GET("/service")
Call<ArrayList<ServiceData>> getData();
}
Service
public class Service{
#SerializedName("data")
private ArrayList<ServiceData> service = new ArrayList<>();
}
Service Data
public class ServiceData {
#SerializedName("id")
private int id;
public ServiceData(int id, String nome) {
this.id = id;
}
public int getId() {
return id;
}
}
Activity
final Call<ArrayList<ServiceData>> service = apiService.getService();
service.enqueue(new Callback<ArrayList<ServiceData>>() {
#Override
public void onResponse(Call<ArrayList<ServiceData>> call, Response<ArrayList<ServiceData>> response) {
Log.e(TAG, "" + response.body());
}
#Override
public void onFailure(Call<ArrayList<ServiceData>> call, Throwable t) {
Log.e(TAG, "" + t);
}
});
You were in the right path but the response is the whole json and not only the data part you want.
I would create the ResponseApi class:
public class ResponseApi {
#SerializedName("_embedded")
private Service embedded;
}
And change on ApiInterface:
Call<ArrayList<ServiceData>> getData();
To:
Call<ResponseApi> getData();
Also in your activity replace all ArrayList<ServiceData> with ResponseApi.
With only this changes your code should work. And then you'll need to add getters in ResponseApi and Service to access the saved data.
UPDATE adding some getters:
We need the possibility to get the ArrayList of ServiceData of services:
public class Service {
// Your current code
public List<ServiceData> getServices() {
return service;
}
}
And also we could create a getter in ResponseApi to get embedded getEmbedded (I'll add the code as info only) but since we only want the services we could create a getter to the list of services getEmbededServices and use this last method.
public class ResponseApi {
// Your current code
public Service getEmbedded() { // Not used, only shown as info
return embedded;
}
public List<ServiceData> getEmbeddedServices() {
return embedded.getServices();
}
}
This way, when you'll receive a ResponseApi object in the onResponse method you can call its getEmbeddedServices to get the List of ServiceData and then you can loop through them to get the ids:
#Override
public void onResponse(Call<ResponseApi> call, Response<ResponseApi> response) {
Log.d(TAG, "services: " + response.getEmbeddedServices());
// Here you can loop the response.getEmbeddedServices() which is a List of ServiceData and get each of the ids. Ex:
for (ServiceData serviceData : response.getEmbeddedServices()) {
Log.d(TAG, "service Id: " + serviceData.getId());
// Here you have access to the ids and can do whatever you need with them.
}
}
By the way, only as a suggestion, I would rename (with refactor in Android Studio) this service var (in Service class):
private ArrayList<ServiceData> service = new ArrayList<>();
To servicesList:
private ArrayList<ServiceData> servicesList = new ArrayList<>();
And maybe also refactor the Service class to ServicesList class.
It's going to work either you rename them or not but, in my opinion, the code is more readable this way.
Try this
Your Parsing mapping has issues try below Model
ServiceData.java
public class ServiceData {
#SerializedName("_links")
#Expose
private Links links;
#SerializedName("_embedded")
#Expose
private Embedded embedded;
#SerializedName("page_count")
#Expose
private Integer pageCount;
#SerializedName("page_size")
#Expose
private Integer pageSize;
#SerializedName("total_items")
#Expose
private Integer totalItems;
#SerializedName("page")
#Expose
private Integer page;
public Links getLinks() {
return links;
}
public void setLinks(Links links) {
this.links = links;
}
public Embedded getEmbedded() {
return embedded;
}
public void setEmbedded(Embedded embedded) {
this.embedded = embedded;
}
public Integer getPageCount() {
return pageCount;
}
public void setPageCount(Integer pageCount) {
this.pageCount = pageCount;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public Integer getTotalItems() {
return totalItems;
}
public void setTotalItems(Integer totalItems) {
this.totalItems = totalItems;
}
public Integer getPage() {
return page;
}
public void setPage(Integer page) {
this.page = page;
}
}
Self_.java
public class Self_ {
#SerializedName("href")
#Expose
private String href;
public String getHref() {
return href;
}
public void setHref(String href) {
this.href = href;
}
}
Self.java
public class Self {
#SerializedName("href")
#Expose
private String href;
public String getHref() {
return href;
}
public void setHref(String href) {
this.href = href;
}
}
Links_.java
public class Links_ {
#SerializedName("self")
#Expose
private Self_ self;
public Self_ getSelf() {
return self;
}
public void setSelf(Self_ self) {
this.self = self;
}
}
Links.java
public class Links {
#SerializedName("self")
#Expose
private Self self;
#SerializedName("first")
#Expose
private First first;
#SerializedName("last")
#Expose
private Last last;
public Self getSelf() {
return self;
}
public void setSelf(Self self) {
this.self = self;
}
public First getFirst() {
return first;
}
public void setFirst(First first) {
this.first = first;
}
public Last getLast() {
return last;
}
public void setLast(Last last) {
this.last = last;
}
}
Last.java
public class Last {
#SerializedName("href")
#Expose
private String href;
public String getHref() {
return href;
}
public void setHref(String href) {
this.href = href;
}
}
First.java
public class First {
#SerializedName("href")
#Expose
private String href;
public String getHref() {
return href;
}
public void setHref(String href) {
this.href = href;
}
}
Embedded.java
public class Embedded {
#SerializedName("data")
#Expose
private List<Datum> data = null;
public List<Datum> getData() {
return data;
}
public void setData(List<Datum> data) {
this.data = data;
}
}
Datum.java
public class Datum {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("nome")
#Expose
private String nome;
#SerializedName("_links")
#Expose
private Links_ links;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public Links_ getLinks() {
return links;
}
public void setLinks(Links_ links) {
this.links = links;
}
}
Try to remove ArrayList from every where and direct use ServiceData
Interface
/**
* Class ApiInterface
*/
public interface ApiInterface
{
#Headers("Accept: application/json")
#GET("/service")
Call<ServiceData> getData();
}
Service Data
public class ServiceData {
#SerializedName("id")
private int id;
public ServiceData(int id, String nome) {
this.id = id;
}
public int getId() {
return id;
}
}
Activity
final Call<ServiceData> service = apiService.getService();
service.enqueue(new Callback<ServiceData>() {
#Override
public void onResponse(Call<ServiceData> call, Response<ServiceData> response) {
Log.e(TAG, "" + response.body());
}
#Override
public void onFailure(Call<ServiceData> call, Throwable t) {
Log.e(TAG, "" + t);
}
});
You call and waiting for List. Call<ArrayList<ServiceData>>
But in the response, you have an object.
[...] - is array (list)
{...} - is object
You need to create classes for all parameters properly.
Just try to look at this service (or similar):
http://www.jsonschema2pojo.org/
Or Android Studio (IDEA) also has a plugin (GsonFormat) for converting JSON.

Android - Retrofit2 - java.security.cert.CertPathValidatorException: Trust anchor for certification path not found

I want to get data from the server (https://data.egov.kz/api/v2/zheke_zhane_zandy_tulgalardy_k1/v6?pretty) as an array of json objects. But I get this Log:
java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
I am using Retrofit2 and here my code:
MainActivity.java
public class MainActivity extends AppCompatActivity
implements GetAdmissionSchedule.GetAdmissionScheduleInterface {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GetAdmissionSchedule getAdmissionSchedule = new GetAdmissionSchedule(this);
getAdmissionSchedule.getAdmissionScheduleList();
}
#Override
public void getAdmissionSchedule(List<AdmissionSchedule> admissionScheduleList) {
// here i get my data
}
}
GetAdmissionSchedule.java
public class GetAdmissionSchedule {
private GetAdmissionScheduleInterface getAdmissionScheduleInterface;
public GetAdmissionSchedule(GetAdmissionScheduleInterface getAdmissionScheduleInterface) {
this.getAdmissionScheduleInterface = getAdmissionScheduleInterface;
}
public interface GetAdmissionScheduleInterface {
void getAdmissionSchedule(List<AdmissionSchedule> admissionScheduleList);
}
public void getAdmissionScheduleList() {
DataEgovApi service = DataEgovBaseURL.getRetrofit();
Call<List<AdmissionSchedule>> call = service.getAdmissionScheduleList();
call.enqueue(new Callback<List<AdmissionSchedule>>() {
#Override
public void onResponse(Call<List<AdmissionSchedule>> call, Response<List<AdmissionSchedule>> response) {
Log.d("MyLogs", "MVD: getAdmissionScheduleList " + response.code());
getAdmissionScheduleInterface.getAdmissionSchedule(response.body());
}
#Override
public void onFailure(Call<List<AdmissionSchedule>> call, Throwable t) {
Log.d("MyLogs", "MVD: getAdmissionScheduleList " + t.getLocalizedMessage());
getAdmissionScheduleInterface.getAdmissionSchedule(null);
}
});
}
}
DataEgovBaseURL.java
public class DataEgovBaseURL {
private static final String BASE_URL = "https://data.egov.kz/";
private static Retrofit retrofit = null;
public static DataEgovApi getRetrofit() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit.create(DataEgovApi.class);
}
}
DataEgovApi.java
public interface DataEgovApi {
#GET("api/v2/zheke_zhane_zandy_tulgalardy_k1/v6?pretty")
Call<List<AdmissionSchedule>> getAdmissionScheduleList();
}
AdmissionSchedule.java (My POJO class)
public class AdmissionSchedule {
#SerializedName("id")
#Expose
private String id;
#SerializedName("vremia")
#Expose
private String vremia;
#SerializedName("adres_ru")
#Expose
private String adresRu;
#SerializedName("doljnost_ru")
#Expose
private String doljnostRu;
#SerializedName("name_ru")
#Expose
private String nameRu;
#SerializedName("data")
#Expose
private String data;
#SerializedName("adres_kz")
#Expose
private String adresKz;
#SerializedName("doljnost_kz")
#Expose
private String doljnostKz;
#SerializedName("name_kz")
#Expose
private String nameKz;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getVremia() {
return vremia;
}
public void setVremia(String vremia) {
this.vremia = vremia;
}
public String getAdresRu() {
return adresRu;
}
public void setAdresRu(String adresRu) {
this.adresRu = adresRu;
}
public String getDoljnostRu() {
return doljnostRu;
}
public void setDoljnostRu(String doljnostRu) {
this.doljnostRu = doljnostRu;
}
public String getNameRu() {
return nameRu;
}
public void setNameRu(String nameRu) {
this.nameRu = nameRu;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public String getAdresKz() {
return adresKz;
}
public void setAdresKz(String adresKz) {
this.adresKz = adresKz;
}
public String getDoljnostKz() {
return doljnostKz;
}
public void setDoljnostKz(String doljnostKz) {
this.doljnostKz = doljnostKz;
}
public String getNameKz() {
return nameKz;
}
public void setNameKz(String nameKz) {
this.nameKz = nameKz;
}
}
You server url is https and certificate is already not valid.
Change https to http and it will work.
Else you can install valid SSL certificate on the server.

Unable to retrieve correct values from rest api (RetroFit)

I am trying to post a request via a JSON body through Retrofit2 in Android.
I am trying to hit api at https://magicspree.com/restaurant/webservice/android/login.
Here is my code.`
Input json body (requests via POST method):
{
"restaurantapikey":"v4Vk2wEkzZfWGxeChavYKLnamLrXaDUJTpiInqeU",
"restaurantusername":"dvar.rddwarka.del",
"restaurantpassword":"password"
}
Restaurant.java(model class):
public class Restaurant {
#SerializedName("restaurantApiKey")
private String restaurantApiKey;
#SerializedName("restaurantUserName")
private String restaurantUserName;
#SerializedName("restaurantPassword")
private String restaurantPassword;
#SerializedName("Status")
#Expose
private String status;
#SerializedName("Text")
#Expose
private String text;
#SerializedName("Restaurant_id")
#Expose
private Integer restaurantId;
public String getRestaurantApiKey() {
return restaurantApiKey;
}
public void setRestaurantApiKey(String restaurantApiKey) {
this.restaurantApiKey = restaurantApiKey;
}
public String getRestaurantUserName() {
return restaurantUserName;
}
public void setRestaurantUserName(String restaurantUserName) {
this.restaurantUserName = restaurantUserName;
}
public String getRestaurantPassword() {
return restaurantPassword;
}
public void setRestaurantPassword(String restaurantPassword) {
this.restaurantPassword = restaurantPassword;
}
public Restaurant(String apiKey, String userName,String password) {
this.restaurantApiKey = apiKey;
this.restaurantUserName = userName;
this.restaurantPassword=password;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Integer getRestaurantId() {
return restaurantId;
}
public void setRestaurantId(Integer restaurantId) {
this.restaurantId = restaurantId;
}
public String toString(){
return "id="+restaurantId+", status="+getStatus()+", text="+getText();
}
}
ApiClient.java:
public class ApiClient {
public static final String BASE_URL =
"https://magicspree.com/restaurant/webservice/android/";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
ApiInterface.java:
public interface ApiInterface {
#POST("login")
Call<Restaurant> loginRestaurant(#Body Restaurant restaurant);
}
My onCreate method:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
Restaurant r=new Restaurant("v4Vk2wEkzZfWGxeChavYKLnamLrXaDUJTpiInqeU","dvar.rddwarka.del","password");
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<Restaurant> call = apiService.loginRestaurant(r);
call.enqueue(new Callback<Restaurant>() {
#Override
public void onResponse(Call<Restaurant> call2, Response<Restaurant> response) {
System.out.println(response.body().toString());
}
#Override
public void onFailure(Call<Restaurant> call, Throwable t) {
}
});
}
Expected output JSON:
{"Status":"Success","Text":"Login Successful","Restaurant_id":27}
The problem is that I am getting the values as Status:Failed, Text:Null, and Restaurant_id:0. I have just started with Retrofit so I do not understand it properly. Please tell me how to retrieve the expected values correctly.
This can be naive but with my eagle eyes :) I see that in Postman your parameter is all in lower case while in your code it is Camel case (restaurantapikey
vs restaurantApiKey )
It might be your backend is implemented with case sensitive parameter.
Change your Restaurant class to use this :
#SerializedName("restaurantapikey")
private String restaurantApiKey;
#SerializedName("restaurantusername")
private String restaurantUserName;
#SerializedName("restaurantpassword")
private String restaurantPassword;

Categories