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.
Related
In getProductById method I am trying to construct Mono<OrderResponse> from
Mono<Book> and Mono<Container> like shown below. The issue is response structure what this method is returning different from what I should get.
public Mono<OrderResponse> getProductById(Integer id) {
Mono<Book> monoBook=Mono.just(id).
flatMap(ops.service(BookingDomainService.class)::getProductById);
Mono<Container> monoCon=Mono.just(id).
flatMap(ops.service(BookingDomainService.class)::getContainerById);
OrderResponse or=new OrderResponse(monoBook,monoCon);
return Mono.just(or);
}
Structure of BOOK, Container and Response class are below.
My Book Class :
#Data
#AllArgsConstructor
#Builder
#NoArgsConstructor
public class Book implements Serializable {
#Id
private Integer id;
#Column
private String name;
#Column
private Long price;
}
Container Class:
public class Container {
private String containerName;
private String description;
public String getContainerName() {
return containerName;
}
public void setContainerName(String containerName) {
this.containerName = containerName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
My Response class:
public class OrderResponse {
private Mono<Book> orderMono;
private Mono<Container> orderContainerMono;
public Mono<Book> getOrderMono() {
return orderMono;
}
public void setOrderMono(Mono<Book> orderMono) {
this.orderMono = orderMono;
}
public Mono<Container> getOrderContainerMono() {
return orderContainerMono;
}
public void setOrderContainerMono(
Mono<Container> orderContainerMono) {
this.orderContainerMono = orderContainerMono;
}
public OrderResponse(Mono<Book> orderMono, Mono<Container> orderContainerMono) {
this.orderMono = orderMono;
this.orderContainerMono = orderContainerMono;
}
}
Final response that is being formed from method getProductById(Integer id) is
{
"orderMono": {
"scanAvailable": true
},
"orderContainerMono": {
"scanAvailable": true
}
}
but I need final response as:
I need final response as below json. How to achieve it.
Response:
{
"Book": {
"id": 12,
"name": "pn",
"price": 128
},
"Container": {
"containerName": " Cname",
"description": "diesc"
}
}
You can use Mono.zip to aggreate the results of multiple Monos into a single one that will be fulfilled when all of the given Monos have produced an item.
public final class OrderResponse {
private final Book book;
private final Container container;
public OrderResponse(Book book, Container container) {
this.book = book;
this.container = container;
}
// ...
}
public Mono<OrderResponse> getProductById(Integer id) {
// replace these lines with your actual calls
Mono<Book> bookMono = Mono.just(new Book(1, "Book 1", 1L));
Mono<Container> containerMono = Mono.just(new Container("A", "B"));
return Mono.zip(bookMono, containerMono)
.map(tuple -> new OrderResponse(tuple.getT1(), tuple.getT2()));
}
If you want to return a OrderResponse object directly instead of it being wrapped in a Mono, you can check out the Mono#block method.
I've tried to set values inside movies ArrayList in BlogRepository class.
but I couldn't find the results in the end.
I want to modify the example so that the storage inside the ArrayList is movies.
so the example works and the results show then the example works.
json data :
[
{
"albumId": 1,
"id": 1,
"title": "accusamus beatae ad facilis cum similique qui sunt",
"url": "https://via.placeholder.com/600/92c952",
"thumbnailUrl": "https://via.placeholder.com/150/92c952"
},
{
"albumId": 1,
"id": 2,
"title": "reprehenderit est deserunt velit ipsam",
"url": "https://via.placeholder.com/600/771796",
"thumbnailUrl": "https://via.placeholder.com/150/771796"
},
{
"albumId": 1,
"id": 3,
"title": "officia porro iure quia iusto qui ipsa ut modi",
"url": "https://via.placeholder.com/600/24f355",
"thumbnailUrl": "https://via.placeholder.com/150/24f355"
}
]
Code:
//
public class BlogRepository {
private ArrayList<Blog2> movies = new ArrayList<>();
private MutableLiveData<List<Blog2>> mutableLiveData = new MutableLiveData<>();
private Application application;
public BlogRepository(Application application){
this.application = application;
}
public MutableLiveData<List<Blog2>> getMutableLiveData() {
RestApiService service = RetrofitInstance.getApiService();
Call<List<BlogWrapper>> call = service.getPopularBlog();
call.enqueue(new Callback<List<BlogWrapper>>(){
#Override
public void onResponse(Call<List<BlogWrapper>> call, Response<List<BlogWrapper>> response) {
List<BlogWrapper> mBlogWrapper = response.body();
for (int i=0; i<mBlogWrapper.size(); i++) {
movies = (ArrayList<Blog2>) mBlogWrapper.get(i).getBlog();
//Log.d("trace_movies : ",""+ movies);
}
}
#Override
public void onFailure(Call<List<BlogWrapper>> call, Throwable t) {
// Toast.makeText(MainActivity.this, "Unable to load users", Toast.LENGTH_SHORT).show();
Log.e("trace_2",""+t.getMessage().toString());
}
});
return mutableLiveData;
}
}
//
public class Blog2 {
#SerializedName("albumId")
private int albumId;
#SerializedName("id")
private int id;
#SerializedName("title")
private String title;
#SerializedName("url")
private String url;
#SerializedName("thumbnailUrl")
private String thumbnailUrl;
public void setAlbumId(int albumId) {
this.albumId = albumId;
}
public void setId(int id) {
this.id = id;
}
public void setTitle(String title) {
this.title = title;
}
public void setUrl(String url) {
this.url = url;
}
public void setThumbnailUrl(String thumbnailUrl) {
this.thumbnailUrl = thumbnailUrl;
}
public int getAlbumId() {
return albumId;
}
public int getId() {
return id;
}
public String getTitle() {
return title;
}
public String getUrl() {
return url;
}
public String getThumbnailUrl() {
return thumbnailUrl;
}
}
///
public class BlogWrapper {
#SerializedName("data")
private List<Blog2> mData;
#SerializedName("error")
private Boolean mError;
#SerializedName("message")
private String mMessage;
#SerializedName("status")
private String mStatus;
public List<Blog2>getBlog() {
return mData;
}
public void setBlog(List<Blog2> data) {
mData = data;
}
public Boolean getError() {
return mError;
}
public void setError(Boolean error) {
mError = error;
}
public String getMessage() {
return mMessage;
}
public void setMessage(String message) {
mMessage = message;
}
public String getStatus() {
return mStatus;
}
public void setStatus(String status) {
mStatus = status;
}
}
///
public interface RestApiService {
#GET("/photos")
public Call<List<BlogWrapper>> getPopularBlog();
}
//
public class RetrofitInstance {
private static Retrofit retrofit = null;
public static final String BASE_URL_ = "https://jsonplaceholder.typicode.com/albums/1/";
// public static final String BASE_URL_ = "https://androidwave.com/api/";
public static RestApiService getApiService() {
Gson gson = new GsonBuilder().setLenient().create();
if (retrofit == null) {
retrofit = new retrofit2.Retrofit
.Builder()
.baseUrl(BASE_URL_)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
}
return retrofit.create(RestApiService.class);
}
}
Try this code, sorry i am away from laptop... mybe you can understand from this. I just swich response object as List<Blog2>, because you need it
call.enqueue(new Callback<List<Blog2>>(){
#Override
public void onResponse(Call<List<Blog2>> call, Response<List<Blog2>> response) {
List<Blog2> mBlogWrapper = response.body();
for (int i=0; i<mBlogWrapper.size(); i++) {
movies.add(mBlogWrapper.get(i));
//Log.d("trace_movies : ",""+ movies);
}
}
});
now you have values from the List, then you can store its value to MutableLivedata.
Also don't forget to change your Retrofit method
public interface RestApiService {
#GET("/photos")
public Call<List<Blog2>> getPopularBlog();
}
I starting out with RxJava and Retrofit and wanted to create a simple app to show a list of 100 cryptocurrencies.
I am making an api call which results in something like this :
{
"Response": "Success",
"Message": "Coin list succesfully returned!",
"BaseImageUrl": "https://www.cryptocompare.com",
"BaseLinkUrl": "https://www.cryptocompare.com",
"Data": {
"LTC": {
"Id": "3808",
"Url": "/coins/ltc/overview",
"ImageUrl": "/media/19782/ltc.png",
"Name": "LTC",
"CoinName": "Litecoin",
"FullName": "Litecoin (LTC)",
"Algorithm": "Scrypt",
"ProofType": "PoW",
"SortOrder": "2"
}
...
},
"Type": 100
}
But all I want from this is "Response" and "Data". Since it is not practical to create a 100 different model classes for each coin, I want to store information of all the coins in a common class named Coin which would look something like this :
public class Coins {
#SerializedName("Algorithm")
private String mAlgorithm;
#SerializedName("CoinName")
private String mCoinName;
#SerializedName("FullName")
private String mFullName;
#SerializedName("FullyPremined")
private String mFullyPremined;
#SerializedName("Id")
private String mId;
#SerializedName("ImageUrl")
private String mImageUrl;
#SerializedName("Name")
private String mName;
#SerializedName("PreMinedValue")
private String mPreMinedValue;
#SerializedName("ProofType")
private String mProofType;
#SerializedName("SortOrder")
private String mSortOrder;
#SerializedName("Sponsored")
private Boolean mSponsored;
#SerializedName("Symbol")
private String mSymbol;
#SerializedName("TotalCoinSupply")
private String mTotalCoinSupply;
#SerializedName("TotalCoinsFreeFloat")
private String mTotalCoinsFreeFloat;
#SerializedName("Url")
private String mUrl;
public String getAlgorithm() {
return mAlgorithm;
}
public void setAlgorithm(String Algorithm) {
mAlgorithm = Algorithm;
}
public String getCoinName() {
return mCoinName;
}
public void setCoinName(String CoinName) {
mCoinName = CoinName;
}
public String getFullName() {
return mFullName;
}
public void setFullName(String FullName) {
mFullName = FullName;
}
public String getFullyPremined() {
return mFullyPremined;
}
public void setFullyPremined(String FullyPremined) {
mFullyPremined = FullyPremined;
}
public String getId() {
return mId;
}
public void setId(String Id) {
mId = Id;
}
public String getImageUrl() {
return mImageUrl;
}
public void setImageUrl(String ImageUrl) {
mImageUrl = ImageUrl;
}
public String getName() {
return mName;
}
public void setName(String Name) {
mName = Name;
}
public String getPreMinedValue() {
return mPreMinedValue;
}
public void setPreMinedValue(String PreMinedValue) {
mPreMinedValue = PreMinedValue;
}
public String getProofType() {
return mProofType;
}
public void setProofType(String ProofType) {
mProofType = ProofType;
}
public String getSortOrder() {
return mSortOrder;
}
public void setSortOrder(String SortOrder) {
mSortOrder = SortOrder;
}
public Boolean getSponsored() {
return mSponsored;
}
public void setSponsored(Boolean Sponsored) {
mSponsored = Sponsored;
}
public String getSymbol() {
return mSymbol;
}
public void setSymbol(String Symbol) {
mSymbol = Symbol;
}
public String getTotalCoinSupply() {
return mTotalCoinSupply;
}
public void setTotalCoinSupply(String TotalCoinSupply) {
mTotalCoinSupply = TotalCoinSupply;
}
public String getTotalCoinsFreeFloat() {
return mTotalCoinsFreeFloat;
}
public void setTotalCoinsFreeFloat(String TotalCoinsFreeFloat) {
mTotalCoinsFreeFloat = TotalCoinsFreeFloat;
}
public String getUrl() {
return mUrl;
}
public void setUrl(String Url) {
mUrl = Url;
}
}
So finally my mapped response class would look like :
public class CoinsListResponse {
private boolean success;
private List<Coins> coinsList;
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public List<Coins> getCoinsList() {
return coinsList;
}
public void setCoinsList(List<Coins> coinsList) {
this.coinsList = coinsList;
}
}
I haven't added #Serialized notations because I don't know what key to annotate it with.
My Retrofit service interface has a method to return the results to this map :
public interface CoinService {
#NonNull
#POST
Observable<CoinsListResponse> getCoinList();
}
Since, I am a starter with Retrofit and RxAndroid, there might be a better method to do this, which I am not aware of. If so, please mention that as well !! I am trying to get my head around this for days but couldn't find any answer on SO as well.
Please Help !!
Change
private List<Coins> coinsList;
to
#SerializedName("Data")
private Map<String, Coins> coinsByName;
You can then either just use coinsByName.values() or call e.g. coinsByName.get("LTC")
Hi, I'm using retrofit for JSON parsing.I got 200 response code, but I didn't get any proper response to my ArrayList. I only get the response to "status" field.Other Fields are getting null. Please Help me.JSON data are given below Thank you :)
//json parsing method
private void load() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
.addConverterFactory(GsonConverterFactory.create()).client(client)
Apiinterface request = retrofit.create(Apiinterface.class);
Call<MyPojo> call = request.newsget(new Newslist_Post("en",0));
call.enqueue(new Callback<MyPojo>() {
#Override
public void onResponse(Call<MyPojo> call, Response<MyPojo> response{
try {
if (response.code() == 200) {
Log.d("act", "onResponse - Status : " +response.code());
Gson gson = new Gson();
TypeAdapter<MyPojo>adapter=gson.getAdapter(MyPojo.class);
try {
if (response.errorBody() != null) {
Toast.makeText(MainActivity.this, "Request Success", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
MyPojo news_model = response.body();
// data = new ArrayList<>(Arrays.asList(news_model.getNews()));
status=news_model.isStatus();
count=news_model.getCount();
data=news_model.getNews();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<MyPojo> call, Throwable t) {
Toast.makeText(MainActivity.this, "Please Check your network",Toast.LENGTH_SHORT).show();
//Log.d("Error",t.getMessage());
}
});}
ModelClass
These model classes are used to parse the JSON, in this model class list get second model class contents
public class MyPojo{
#SerializedName("status")
private boolean status;
#SerializedName("count")
private int count;
#SerializedName("news")
private List<News>news;
public int getCount() {
return count;
}
public List<News> getNews() {
return news;
}
public boolean isStatus() {
return status;
}
Second ModelClass
In this model class contains news data, this news data get in the first model class list.
public class News
{
private String news_id;
private String newss_description;
private String newss_title;
private String news_image;
private String lang;
public String getNews_id ()
{
return news_id;
}
public String getNewss_description ()
{
return newss_description;
}
public String getNewss_title ()
{
return newss_title;
}
public String getNews_image ()
{
return news_image;
}
public String getLang ()
{
return lang;
}
}
//JSON
{
"status": true,
"count": 2,
"news": [
{
"news_id": "2",
"news_image": "5fc2eaf170e6fc8ba6aa3974ce0c2e11.jpg",
"newss_title": "new 1",
"newss_description": "test news",
"lang": "en"
},
{
"news_id": "1",
"news_image": "31e3650272d006d24ac6c5fd580cace0.jpg",
"newss_title": "cooking class with tanya in the name of healthy",
"newss_description": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
"lang": "en"
}
]
}
SerializedName and Expose is missing for news model item
#SerializedName("code")
#Expose
Change your News.class like this.
public class News {
#SerializedName("news_id")
#Expose
private String news_id;
#SerializedName("newss_description")
#Expose
private String newss_description;
#SerializedName("newss_title")
#Expose
private String newss_title;
#SerializedName("news_image")
#Expose
private String news_image;
#SerializedName("lang")
#Expose
private String lang;
public String getNews_id() {
return news_id;
}
public String getNewss_description() {
return newss_description;
}
public String getNewss_title() {
return newss_title;
}
public String getNews_image() {
return news_image;
}
public String getLang() {
return lang;
}
}
Change your MyPojo and News class like below
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("status")
#Expose
private Boolean status;
#SerializedName("count")
#Expose
private Integer count;
#SerializedName("news")
#Expose
private List<News> news = null;
public Boolean getStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
public List<News> getNews() {
return news;
}
public void setNews(List<News> news) {
this.news = news;
}
}
// News class
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class News {
#SerializedName("news_id")
#Expose
private String newsId;
#SerializedName("news_image")
#Expose
private String newsImage;
#SerializedName("newss_title")
#Expose
private String newssTitle;
#SerializedName("newss_description")
#Expose
private String newssDescription;
#SerializedName("lang")
#Expose
private String lang;
public String getNewsId() {
return newsId;
}
public void setNewsId(String newsId) {
this.newsId = newsId;
}
public String getNewsImage() {
return newsImage;
}
public void setNewsImage(String newsImage) {
this.newsImage = newsImage;
}
public String getNewssTitle() {
return newssTitle;
}
public void setNewssTitle(String newssTitle) {
this.newssTitle = newssTitle;
}
public String getNewssDescription() {
return newssDescription;
}
public void setNewssDescription(String newssDescription) {
this.newssDescription = newssDescription;
}
public String getLang() {
return lang;
}
public void setLang(String lang) {
this.lang = lang;
}
}
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.