I have created some Json file that contains shop's objects and i want to store it on Google drive and read it with Retrofit.
Currently, I can't store it in local memory or in-app.
Also, there is no server side yet, so it needs to be stored somewhere that Retrofit can access.
If you have any other ideas, I'd be more than happy to hear.
I make the link public to anyone, and here is my .json file:
{
"shop": [
{
"shopName": "Renuar",
"shopID": "1000",
"isPaid": "false",
"branches": [
{
"branchName": "Branch 1",
"branchPhone": "039599559",
"openingTime": "09:00",
"closingTime": "21:00",
"branchLat": "32.000",
"branchLon": "35.000",
"branchAddressNote": "Grand Canyon"
}
]
},
{
"shopName": "Castro",
"shopID": "1000",
"isPaid": "false",
"branches": [
{
"branchName": "Branch 1",
"branchPhone": "039599559",
"openingTime": "09:00",
"closingTime": "21:00",
"branchLat": "32.000",
"branchLon": "35.000",
"branchAddressNote": "Grand Canyon"
}
]
}
]
}
I've tried the next steps but it's not work for me.
public interface ApiService {
#GET("file/d/1-lsBIzI7Y5uCg8bG_531o49Dcu6E2RdH/view?usp=sharing")
Call<ShopsResponse> getAllShops();
}
public static class RetrofitInstance{
public static Retrofit retrofit = null;
private static final String BASE_URL = "https://drive.google.com/";
public static ApiService getApiService(){
if (retrofit == null){
Gson gson = new GsonBuilder()
.setLenient()
.create();
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
}
return retrofit.create(ApiService.class);
}
}
ApiService apiService = RetrofitInstance.getApiService();
apiService.getAllShops().enqueue(new Callback<ShopsResponse>() {
#Override
public void onResponse(Call<ShopsResponse> call, Response<ShopsResponse> response) {
ShopsResponse response1 = response.body();
Log.d(TAG, "onResponse: "+response1.getShop().size());
}
#Override
public void onFailure(Call<ShopsResponse> call, Throwable t) {
Log.d(TAG, "onResponse: "+t.getMessage());
}
});
That what i receive in logcat:
D/myDebug: onResponse: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 2 column 1 path $
I think there is something wrong with your pojo objects. It should be like this according to your response
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Branch {
#SerializedName("branchName")
#Expose
private String branchName;
#SerializedName("branchPhone")
#Expose
private String branchPhone;
#SerializedName("openingTime")
#Expose
private String openingTime;
#SerializedName("closingTime")
#Expose
private String closingTime;
#SerializedName("branchLat")
#Expose
private String branchLat;
#SerializedName("branchLon")
#Expose
private String branchLon;
#SerializedName("branchAddressNote")
#Expose
private String branchAddressNote;
public String getBranchName() {
return branchName;
}
public void setBranchName(String branchName) {
this.branchName = branchName;
}
public String getBranchPhone() {
return branchPhone;
}
public void setBranchPhone(String branchPhone) {
this.branchPhone = branchPhone;
}
public String getOpeningTime() {
return openingTime;
}
public void setOpeningTime(String openingTime) {
this.openingTime = openingTime;
}
public String getClosingTime() {
return closingTime;
}
public void setClosingTime(String closingTime) {
this.closingTime = closingTime;
}
public String getBranchLat() {
return branchLat;
}
public void setBranchLat(String branchLat) {
this.branchLat = branchLat;
}
public String getBranchLon() {
return branchLon;
}
public void setBranchLon(String branchLon) {
this.branchLon = branchLon;
}
public String getBranchAddressNote() {
return branchAddressNote;
}
public void setBranchAddressNote(String branchAddressNote) {
this.branchAddressNote = branchAddressNote;
}
}
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("shop")
#Expose
private List<Shop> shop = null;
public List<Shop> getShop() {
return shop;
}
public void setShop(List<Shop> shop) {
this.shop = shop;
}
}
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Shop {
#SerializedName("shopName")
#Expose
private String shopName;
#SerializedName("shopID")
#Expose
private String shopID;
#SerializedName("isPaid")
#Expose
private String isPaid;
#SerializedName("branches")
#Expose
private List<Branch> branches = null;
public String getShopName() {
return shopName;
}
public void setShopName(String shopName) {
this.shopName = shopName;
}
public String getShopID() {
return shopID;
}
public void setShopID(String shopID) {
this.shopID = shopID;
}
public String getIsPaid() {
return isPaid;
}
public void setIsPaid(String isPaid) {
this.isPaid = isPaid;
}
public List<Branch> getBranches() {
return branches;
}
public void setBranches(List<Branch> branches) {
this.branches = branches;
}
}
Related
I am getting this response from my Express API Call.
Here's the Response:
{
"responseData": [{
"unitNames": [
"Matrices",
"Complex Numbers"
],
"subject": "maths",
"unitTopics": {
"1": [{
"topicName": "1.1 Introduction",
"topicURL": ""
},
{
"topicName": "1.2 Square Matrix",
"topicURL": ""
}
],
"2": [{
"topicName": "2.1 Numbers",
"topicURL": ""
}
]
}
}]
}
I got the response by using Retrofit in Android. It works great.But it can't parse Objects
Here's my Problem in Android Side.
{
"responseData": [{
"unitNames": [
"Matrices",
"Complex Numbers"
],
"subject": "maths",
"unitTopics": {
"1": [[Object],
[Object]
],
"2": [[Object]
]
}
}]
}
Its showing Object instead of my Data. How to fix this
Here's the Code:
System.out.println(response.body().getResponseData())
String received_data = response.body().getResponseData();
received_data_sub_units_topics_json = new JSONArray("["+received_data+"]");
System.out.println("MAIN2 "+received_data_sub_units_topics_json);
After converting to jsonarray, it shows like this,
{
"responseData": [{
"unitNames": [
"Matrices",
"Complex Numbers"
],
"subject": "maths",
"unitTopics": {
"1": [["Object"],
["Object"]
],
"2": [["Object"]
]
}
}]
}
Please help me with some solutions
For json i always use the library com.fasterxml.jackson.
You can use too org.json.JSONArray, org.json.JSONObject.
Here is an example of each one:
1- jackson
For implements this (is a bit long but you will convert it to java classes, so, you will can edit the values and obtain it more easily than if you use JSONObject), you have to create classes wich has the same structure than your json:
public class principalClass {
ArrayList<ResponseData> responseData;
...
//Getters, setters and constructors
}
public class ResponseData {
public ArrayList<String> unitNames;
public String subject;
public UnitTopics unitTopics;
...
//Getters, setters and constructors
}
public class UnitTopics {
public ArrayList<Topics> first;
public ArrayList<Topics> second;
...
//Getters, setters and constructors
}
public class Topics {
public String topicName;
public String topicURL;
...
//Getters, setters and constructors
}
Something like that, and then you use jackson to pass your json to you class principalClass:
ObjectMapper obj= new ObjectMapper();
PrincipalClass principal= obj.readValue(json, PrincipalClass.class);
The second posibility is to convert the values to JSONArray and JSONObject:
JSONObject bodyJSON = new JSONObject(json);
JSONArray responseData = bodyJSON.getJSONArray("responseData");
JSONArray unitNames= responseData.getJSONArray(0);
JSONObject subject= responseData.getJSONObject(1);
...
And if u want, u can loop through a JSONArray:
for (int i = 0; i < unitNames.length(); i++) {
String element = unitNames.getString(i);
}
You can use gson converter with retrofit to convert your json data to java object model class
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
Or you can convert json data to model class like
Gson gson = new Gson();
String jsonInString = "{your json data}";
ResponseModel response= gson.fromJson(jsonInString, ResponseModel.class);
Hey have you tried converting this JSON Object to a POJO.
I'd recommend using:
This website
It saves a lot of time and effort.
These will be your model classes:
package com.example.app;
import java.io.Serializable;
import java.util.List;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class ResponseDatum implements Serializable
{
#SerializedName("unitNames")
#Expose
private List<String> unitNames = null;
#SerializedName("subject")
#Expose
private String subject;
#SerializedName("unitTopics")
#Expose
private UnitTopics unitTopics;
public ResponseDatum() {
}
public ResponseDatum(List<String> unitNames, String subject, UnitTopics unitTopics) {
super();
this.unitNames = unitNames;
this.subject = subject;
this.unitTopics = unitTopics;
}
public List<String> getUnitNames() {
return unitNames;
}
public void setUnitNames(List<String> unitNames) {
this.unitNames = unitNames;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public UnitTopics getUnitTopics() {
return unitTopics;
}
public void setUnitTopics(UnitTopics unitTopics) {
this.unitTopics = unitTopics;
}
}
package com.example.app;
import java.io.Serializable;
import java.util.List;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class ResponseObject implements Serializable
{
#SerializedName("responseData")
#Expose
private List<ResponseDatum> responseData = null;
public ResponseObject() {
}
public ResponseObject(List<ResponseDatum> responseData) {
super();
this.responseData = responseData;
}
public List<ResponseDatum> getResponseData() {
return responseData;
}
public void setResponseData(List<ResponseDatum> responseData) {
this.responseData = responseData;
}
}
package com.example.app;
import java.io.Serializable;
import java.util.List;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class UnitTopics implements Serializable
{
#SerializedName("1")
#Expose
private List<com.example.app._1> _1 = null;
#SerializedName("2")
#Expose
private List<com.example.app._2> _2 = null;
public UnitTopics() {
}
public UnitTopics(List<com.example.app._1> _1, List<com.example.app._2> _2) {
super();
this._1 = _1;
this._2 = _2;
}
public List<com.example.app._1> get1() {
return _1;
}
public void set1(List<com.example.app._1> _1) {
this._1 = _1;
}
public List<com.example.app._2> get2() {
return _2;
}
public void set2(List<com.example.app._2> _2) {
this._2 = _2;
}
}
package com.example.app;
import java.io.Serializable;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class _1 implements Serializable
{
#SerializedName("topicName")
#Expose
private String topicName;
#SerializedName("topicURL")
#Expose
private String topicURL;
public _1() {
}
public _1(String topicName, String topicURL) {
super();
this.topicName = topicName;
this.topicURL = topicURL;
}
public String getTopicName() {
return topicName;
}
public void setTopicName(String topicName) {
this.topicName = topicName;
}
public String getTopicURL() {
return topicURL;
}
public void setTopicURL(String topicURL) {
this.topicURL = topicURL;
}
}
package com.example.app;
import java.io.Serializable;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class _2 implements Serializable
{
#SerializedName("topicName")
#Expose
private String topicName;
#SerializedName("topicURL")
#Expose
private String topicURL;
public _2() {
}
public _2(String topicName, String topicURL) {
super();
this.topicName = topicName;
this.topicURL = topicURL;
}
public String getTopicName() {
return topicName;
}
public void setTopicName(String topicName) {
this.topicName = topicName;
}
public String getTopicURL() {
return topicURL;
}
public void setTopicURL(String topicURL) {
this.topicURL = topicURL;
}
}
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 am getting null response in place of value.
My json response is
{
"resonse": {
"status": 200,
"result": [
{
"video_id": "3c19979979",
"video_title": "Sushil Kumar Modi press conference after serial bomb blasts at Modi rally in Patna",
"video_description": "BJP at Patna serial blast in Bihar, Nitish government has stood in the dock. Former Deputy Chief Minister Sushil Kumar Modi said the blasts Narendra Modi were targeted. He said that Nitish Kumar look Modi as the enemy.<br />\r\n",
"video_poster": "https://vbcdn.com/cdn/download/2013102913830306761810268995.jpg",
"video_duration": "02:02",
"video_category": "News/Politics",
}
]}
}
Retrofit client :
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request newRequest = chain.request().newBuilder()
.addHeader("Authorization", "Bearer " + token)
.build();
return chain.proceed(newRequest);
}
}).build();
if (retrofit==null)
retrofit = new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
return retrofit;
API CLIENT :
#Headers("Content-Type:application/json")
#POST("video/list-video.php")
Call<ResponseVideoList> getVideoListFromSearchText(#Body JsonObject jsonObject);
POJO class is:
public class ResponseVideoList implements Serializable{
#SerializedName("resonse")
#Expose
private Resonse resonse;
private final static long serialVersionUID = -2645239251698186770L;
public Resonse getResonse() {
return resonse;
}
public void setResonse(Resonse resonse) {
this.resonse = resonse;
}
public class Resonse implements Serializable
{
#SerializedName("status")
#Expose
private String status;
#SerializedName("result")
#Expose
private List<VIdeoItem> result = null;
private final static long serialVersionUID = -350882274147346830L;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public List<VIdeoItem> getResult() {
return result;
}
public void setResult(List<VIdeoItem> result) {
this.result = result;
}
}
}
Whenever I call the api , the statuscode is 200 but the response body is always coming as null.
the message i received is this :
Response{protocol=h2, code=200, message=, url=https://api.com/video/list-video.php}
Any help or suggestion is appreciated .
Just for new people who comes here with this error.. it can also happens when your data classes (model) does not correspond to the json you are consuming.
You can validate this by setting the onResponse() method from Retrofit to Any (kotlin) or to an Object (java)
#Override
public void onResponse(Call<Object> call, Response<Object> response) {
Log.d("zzz", "debug this line and check if response have ur object");
}
Seems the returned JSON is not well formatted (unless you cropped the file to paste it here...)
I used JSONLint to validate it
On first look your json seems wrong theres an additional ",", after "video_category": "News/Politics", <--- maybe thats the problem
Btw i would do my pojo like this
i used this site to create it automatically http://www.jsonschema2pojo.org/
you can always use this site to validate your JSON https://jsonformatter.curiousconcept.com/
-----------------------------------ResponseVideoList.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class ResponseVideoList{
#SerializedName("resonse")
#Expose
private Resonse resonse;
public Resonse getResonse() {
return resonse;
}
public void setResonse(Resonse resonse) {
this.resonse = resonse;
}
}
-----------------------------------Resonse.java-----------------------------------
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Resonse {
#SerializedName("status")
#Expose
private Integer status;
#SerializedName("result")
#Expose
private List<Result> result = null;
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public List<Result> getResult() {
return result;
}
public void setResult(List<Result> result) {
this.result = result;
}
}
-----------------------------------Result.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Result {
#SerializedName("video_id")
#Expose
private String videoId;
#SerializedName("video_title")
#Expose
private String videoTitle;
#SerializedName("video_description")
#Expose
private String videoDescription;
#SerializedName("video_poster")
#Expose
private String videoPoster;
#SerializedName("video_duration")
#Expose
private String videoDuration;
#SerializedName("video_category")
#Expose
private String videoCategory;
public String getVideoId() {
return videoId;
}
public void setVideoId(String videoId) {
this.videoId = videoId;
}
public String getVideoTitle() {
return videoTitle;
}
public void setVideoTitle(String videoTitle) {
this.videoTitle = videoTitle;
}
public String getVideoDescription() {
return videoDescription;
}
public void setVideoDescription(String videoDescription) {
this.videoDescription = videoDescription;
}
public String getVideoPoster() {
return videoPoster;
}
public void setVideoPoster(String videoPoster) {
this.videoPoster = videoPoster;
}
public String getVideoDuration() {
return videoDuration;
}
public void setVideoDuration(String videoDuration) {
this.videoDuration = videoDuration;
}
public String getVideoCategory() {
return videoCategory;
}
public void setVideoCategory(String videoCategory) {
this.videoCategory = videoCategory;
}
}
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.
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;
}
}