Get data from nested json object inside json array in android - java

I am trying to get data from json that work for first portion but not for nested json object.I want to get the province and city from json object.
I am trying to get data from json that work for first portion but not for nested json object.I want to get the province and city from json object.
In province object i want province string and in city i want city string
........................MY JSON.................
{
"ads": [
{
"id": 8,
"title": "Software Engineering",
"description": "A book for software engineers",
"price": 100,
"user_id": 1,
"province_id": 4,
"city_id": 5,
"subject_id": 1,
"level_id": 3,
"active": 1,
"created_at": "2019-04-20 04:35:00",
"updated_at": "2019-04-20 04:35:00",
"province": {
"id": 4,
"province": "Blochistan",
"created_at": null,
"updated_at": null
},
"city": {
"id": 5,
"city": "Quetta",
"province_id": 4,
"created_at": null,
"updated_at": null
}
}
]
}
public class AdsAdapter extends RecyclerView.Adapter<AdsAdapter.CustomViewHolder> {
private List<Data> adsList;
private Context context;
public AdsAdapter(List<Data> dataList,Context context) {
this.adsList=dataList;
this.context=context;
}
#NonNull
#Override
public CustomViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.ads_list, viewGroup, false);
return new CustomViewHolder(itemView,adsList,context);
}
#Override
public void onBindViewHolder(#NonNull CustomViewHolder customViewHolder, int i) {
Data data = adsList.get(i);
customViewHolder.ad_title.setText(data.getTitle());
customViewHolder.ad_price.setText(data.getPrice().toString());
// customViewHolder.ad_city.setText(();
}
#Override
public int getItemCount() {
return adsList.size();
}
public class CustomViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView ad_title,ad_price,ad_province,ad_city;
private List<Data> adsList;
private Context context;
public CustomViewHolder(#NonNull View itemView,List<Data> adsList,Context context) {
super(itemView);
this.adsList=adsList;
this.context=context;
itemView.setOnClickListener(this);
ad_title = (TextView)itemView.findViewById(R.id.current_page);
ad_price = itemView.findViewById(R.id.ad_price);
ad_province = itemView.findViewById(R.id.province);
ad_city = itemView.findViewById(R.id.city);
}
#Override
public void onClick(View v) {
int position=getAdapterPosition();
Data data = this.adsList.get(position);
Intent intent = new Intent(this.context,AdDetail.class);
intent.putExtra("title",data.getTitle());
intent.putExtra("discrip",data.getDescription());
intent.putExtra("price",data.getPrice().toString());
intent.putExtra("create",data.getCreatedAt().toString());
this.context.startActivity(intent);
}
}
}
my application terminated when i access province string.
Model Class
public class Province {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("province")
#Expose
private String province;
#SerializedName("created_at")
#Expose
private Object createdAt;
#SerializedName("updated_at")
#Expose
private Object updatedAt;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public Object getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Object createdAt) {
this.createdAt = createdAt;
}
public Object getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Object updatedAt) {
this.updatedAt = updatedAt;
}
}
Call call = api.getAds(parse_subject_id,parse_level_id);
/**
* Enqueue Callback will be call when get response...
*/
call.enqueue(new Callback<SubjectList>() {
#Override
public void onResponse(Call<SubjectList> call, Response<SubjectList> response) {
pDialog.dismiss();
if (response.isSuccessful()) {
/**
* Got Successfully
*/
adsList = response.body().getAds();
recyclerView = (RecyclerView) findViewById(R.id.recycler_view_Ads);
adsAdapter = new AdsAdapter(adsList,getApplicationContext());
RecyclerView.LayoutManager eLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(eLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adsAdapter);
/////////////////////////////////////
}
}
#Override
public void onFailure(Call<SubjectList> call, Throwable t) {
pDialog.dismiss();
}
});
hare i am calling the adapter and pass parameters

From city object you can directly get province_id

Related

Save the edittext data of a dynamic generated forms to server

I have generated dynamic forms according to type i.e String, int and spinner according to the json data provided by backend.
I have created a recylerview adapter and in pojo class I have added extra variable as answer and provided setter method to it.
Now, forms have generated according to type but I need to save data to server. To save data, i need to get each edittext value with respective id and type and I need to loop it but I couldnot do it so. I cannot define the edittext value with its ID and type. I hope you guys will help me.
There are three paramters to post to server,in method callRetrofitSaveForm() i. vendorId, ii. userid
iii. formData, I have problem with param iii because it has its format to pass. I have used retrofit to parse and problem is with third parameter formData.
the value format of third paramter is
[{"id":"24","label":"Customer ID","value":"102"},{"id":"25","label":"Amount","value":"2000"}]
My Adapter
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
HelpForm.FormSetting formSetting=formArrayList.get(position);
final String description = formArrayList.get(position).getLabel();
Log.d("cjjdnjcnjd",description);
if (formSetting.getType().equals("STRING")){
Log.d("dndjkd",String.valueOf(holder.getAdapterPosition()));
holder.textViewString = new TextView(activity);
holder.linearLayout.addView(holder.textViewString);
holder.textViewString.setText(formSetting.getLabel());
holder.textViewString.setPadding(24, 4, 24, 2);
holder.textViewString.setTextColor(context.getResources().getColor(R.color.colorTexts));
holder.textViewString.setTextSize(15);
holder.editTextString = new EditText(activity);
holder.linearLayout.addView(holder.editTextString);
editTextListString.add(holder.editTextString);
}
if (formSetting.getType().equals("INT")){
holder.textViewInt = new TextView(activity);
holder.linearLayout.addView(holder.textViewInt);
holder.textViewInt.setText(formSetting.getLabel());
holder.textViewInt.setPadding(24, 4, 24, 2);
holder.textViewInt.setTextColor(context.getResources().getColor(R.color.colorTexts));
holder.textViewInt.setTextSize(15);
holder.editTextINT = new EditText(activity);
holder.linearLayout.addView(holder.editTextINT);
}
if (formSetting.getType().equals("DATE")){
holder.textViewDate = new TextView(activity);
holder.linearLayout.addView(holder.textViewDate);
holder.textViewDate.setText(formSetting.getLabel());
holder.textViewDate.setPadding(24, 4, 24, 2);
holder.textViewDate.setTextColor(context.getResources().getColor(R.color.colorTexts));
holder.textViewDate.setTextSize(15);
holder.editTextDate = new EditText(activity);
holder.linearLayout.addView(holder.editTextDate);
}
if(formSetting.getType().equals("DROPDOWN")){
holder.textViewSpinner = new TextView(context);
holder.linearLayout.addView(holder.textViewSpinner);
holder.textViewSpinner.setText(formSetting.getLabel());
holder.textViewSpinner.setPadding(16, 4, 8, 4);
holder.spinner = new Spinner(context);
holder.linearLayout.addView(holder.spinner);
ArrayList<String> err = new ArrayList<>();
err = formSetting.getOptions();
holder.spinner.setAdapter(new ArrayAdapter<String>(context, android.R.layout.simple_dropdown_item_1line, err));
}
VendorFormActivity.save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
callRetrofitSaveForm();
}
});
}
#Override
public int getItemCount() {
return formArrayList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView textViewString,textViewInt,textViewDate;
LinearLayout linearLayout;
EditText editTextString,editTextINT,editTextDate;
Spinner spinner;
TextView textViewSpinner;
public MyViewHolder(View itemView) {
super(itemView);
linearLayout=itemView.findViewById(R.id.dynamiccontainer);
}
}
JSON Response
{
"status": "200",
"message": "success",
"formSetting": [
{
"label": "Customer ID",
"id": 24,
"type": "INT"
},
{
"label": "Amount",
"id": 25,
"type": "INT"
}
]
}
HelpForm
public class HelpForm {
#SerializedName("status")
#Expose
public String status;
#SerializedName("message")
#Expose
public String message;
#SerializedName("formSetting")
#Expose
public ArrayList<FormSetting> formSetting = null;
public ArrayList<FormSetting> getFormSetting() {
return formSetting;
}
public String getStatus() {
return status;
}
public String getMessage() {
return message;
}
public class FormSetting {
#SerializedName("options")
#Expose
public ArrayList<String> options = null;
#SerializedName("label")
#Expose
public String label;
#SerializedName("id")
#Expose
public String id;
#SerializedName("type")
#Expose
public String type;
#SerializedName("answer")
#Expose
public String answer;
public ArrayList<String> getOptions() {
return options;
}
public String getLabel() {
return label;
}
public String getId() {
return id;
}
public String getType() {
return type;
}
public void setAnswer(String answer) {
this.answer = answer;
}
}
}
public void callRetrofitSaveForm() {
RestClient.RetroInterfaceAPI mInterface = RestClient.getClient();
Call<SaveForm> call = mInterface.getSaveForm( vendorID, userID,formData);
call.enqueue(new Callback<SaveForm>() {
#Override
public void onResponse(Call<SaveForm> call, Response<SaveForm> response) {
if (response.body() != null) {
}
}
#Override
public void onFailure(Call<SaveForm> call, Throwable t) {
}
});
}
}
You can grab the parent view and loop through it and get all editText.
private HashSet<EditText> getTextViews(ViewGroup root){
HashSet<EditText> views=new HashSet<>();
for(int i=0;i<root.getChildCount();i++){
View v=root.getChildAt(i);
if(v instanceof EditText){
views.add((EditText)v);
}else if(v instanceof ViewGroup){
views.addAll(getTextViews((ViewGroup)v));
}
}
return views;
}

response.body().getBasketShopList is empty, but API JSON in Postman is not empty

I am new to Android, it's about a week that I am spending 3 hours a day on this problem but still I can not find a solution, I am going to get a list of object from server and pass them to Adapter and another process. But I got into trouble, there is no error, in my Android Studio I got " response.code = 200 " but a list of my object is empty although in Postman with same authorization and same username a list of object is not empty. I don't know what should I do, so finally I forced to ask my question hear.
First let's take a look on Postman
Body : :
Authorization : :
Now when I clicked on Send Button in Postman I got "code: 200" and hear is the response Body:
{
"results": [
{
"_id": "5c7e69d283c0b00001108fad",
"count": 2,
"productId": "5ba51d877246b700016ec205",
"username": "rezash",
"createdAt": "2019-03-05T12:21:38.196UTC",
"updatedAt": "2019-03-05T12:36:11.058UTC",
"ACL": {
"*": {
"read": true,
"write": true
}
}
},
{
"_id": "5c7e69d483c0b00001108fae",
"count": 4,
"productId": "5acc0f2c790c0c000132c984",
"username": "rezash",
"createdAt": "2019-03-05T12:21:40.338UTC",
"updatedAt": "2019-03-05T12:36:15.830UTC",
"ACL": {
"*": {
"read": true,
"write": true
}
}
}
]
}
In my OnlineShopAPI Interface:
public interface OnlineShopAPI {
String BASE_URL = "https://api.backtory.com/";
#Headers("X-Backtory-Object-Storage-Id:5a154d2fe4b03ffa0436a535")
#HTTP(method = "POST" , path = "object-storage/classes/query/Basket" , hasBody = true)
Call<MainBasketShopResponse> mainBasketShop (
#Header("Authorization") String authorization,
#Body BasketShop basketShop
);
interface getMainBasketShop {
void onResponse(List<BasketShop> basketShopList);
void onFailure(String cause);
}
}
My MainBasketShopResponse class:
public class MainBasketShopResponse {
#SerializedName("results")
List<BasketShop> basketShopList;
public MainBasketShopResponse() {
}
public List<BasketShop> getBasketShopList() {
return basketShopList;
}
public void setBasketShopList(List<BasketShop> basketShopList) {
this.basketShopList = basketShopList;
}
}
BasketShop class:
public class BasketShop {
#SerializedName("username")
private String username;
#SerializedName("productId")
private String productId;
#SerializedName("count")
private float count;
#SerializedName("createdAt")
private String createdAt;
#SerializedName("_id")
private String id;
public String getCreatedAt() {
return createdAt;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public BasketShop(String username) {
this.username = username;
}
public BasketShop() {
}
public BasketShop(String username, String productId, float count) {
this.username = username;
this.productId = productId;
this.count = count;
}
public BasketShop(String createdAt, String id) {
this.createdAt = createdAt;
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public float getCount() {
return count;
}
public void setCount(float count) {
this.count = count;
}
}
My Controller that contain retrofit:
public class MainBasketShopController {
OnlineShopAPI.getMainBasketShop getMainBasketShop;
public MainBasketShopController(OnlineShopAPI.getMainBasketShop getMainBasketShop) {
this.getMainBasketShop = getMainBasketShop;
}
public void start(String authorization , BasketShop basketShop){
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(OnlineShopAPI.BASE_URL)
.build();
OnlineShopAPI onlineShopAPI = retrofit.create(OnlineShopAPI.class);
Call<MainBasketShopResponse> call = onlineShopAPI.mainBasketShop(authorization , basketShop);
call.enqueue(new Callback<MainBasketShopResponse>() {
#Override
public void onResponse(Call<MainBasketShopResponse> call, Response<MainBasketShopResponse> response) {
if (response.isSuccessful()) {
Log.d("emptyhst1" , response.body().getBasketShopList().toString());
Log.d("emptyhst2" , Integer.toString(response.body().getBasketShopList().size()));
getMainBasketShop.onResponse(response.body().getBasketShopList());
}
}
#Override
public void onFailure(Call<MainBasketShopResponse> call, Throwable t) {
getMainBasketShop.onFailure(t.getMessage());
}
});
}
}
Hear is a part of my BasketShopFragment that I call MainBasketShopController with it:
MainBasketShopController mainBasketShopController = new MainBasketShopController(getMainBasketShop);
BasketShop basketShop = new BasketShop();
basketShop.setUsername(MyPreferenceManager.getInstance(getContext()).getUsername());
mainBasketShopController.start(
"bearer " + MyPreferenceManager.getInstance(getContext()).getAccessToken() ,
basketShop
);
OnlineShopAPI.getMainBasketShop getMainBasketShop = new OnlineShopAPI.getMainBasketShop() {
#Override
public void onResponse(List<BasketShop> basketShopList) {
Log.d("emptyhst3" , basketShopList.toString());
basketShopList2.clear();
basketShopList2.addAll(basketShopList);
mainBasketShopAdapter.notifyDataSetChanged();
}
#Override
public void onFailure(String cause) {
Toast.makeText(getContext(), cause , Toast.LENGTH_SHORT).show();
}
};
I checked both of username and accessToken that i passed to the controller and I am sure that everything is looking like in Postman
After a week I found a solution , I just changed a variable "float count" to "String count" from my Model(BasketShop Class) Ops!
#SerializedName("count")
private String count;
Can you show us your Logs?
What got printed in this block?
if (response.isSuccessful()) {
Log.d("emptyhst1" , response.body().getBasketShopList().toString());
Log.d("emptyhst2" , Integer.toString(response.body().getBasketShopList().size()));
getMainBasketShop.onResponse(response.body().getBasketShopList());
}

Retrofit / Gson puts empty model in List<>

Im trying to retrive json with retrofit and gson from the API http://api.themoviedb.org/3/movie/. Im my main activity it is working fine, but when i call some additional information in my DetailsActivity i figure out that the models in my array are emty. This is weird because i am recieving even the right number of objects in the array from the api. But when i Log a value from the model (for example Log.d(TAG, movieTrailers.get(0).getName()) the app crashes. Whit an if statement i figure out that this value is null.
This is the API http://api.themoviedb.org/3/movie/297802/videos?api_key= for example. (Unfortunatly i am not allowed to post the api key) It contains in a jsonarray of videos about the movie.
This is my Code:
The Model:
public class MovieTrailer {
#SerializedName("key")
private String key;
#SerializedName("name")
private String name;
#SerializedName("type")
private String type;
public MovieTrailer(String key, String name, String type){
this.key = key;
this.name = name;
this.type = type;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
The Model for the List:
public class TrailersList {
#SerializedName("results")
#Expose
private List<MovieTrailer> trailers = null;
public List<MovieTrailer> getTrailers() {
return trailers;
}
public void setTrailers(List<MovieTrailer> trailers) {
this.trailers = trailers;
}
}
The Adapter:
public class VideoAdapter extends RecyclerView.Adapter<VideoAdapter.VideoAdapterViewHolder> {
private List<MovieTrailer> movieTrailers;
private final VideoOnClickHandler videoOnClickHandler;
public interface VideoOnClickHandler{
void onClick(MovieTrailer movieTrailer);
}
public VideoAdapter(VideoOnClickHandler onClickHandler) {videoOnClickHandler = onClickHandler;}
public class VideoAdapterViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public final TextView videoTypeText;
public final TextView videoNameText;
public VideoAdapterViewHolder(View view){
super(view);
videoTypeText = (TextView) view.findViewById(R.id.tv_video_type);
videoNameText = (TextView) view.findViewById(R.id.tv_video_name);
view.setOnClickListener(this);
}
#Override
public void onClick(View view) {
int adapterPosition = getAdapterPosition();
MovieTrailer movieTrailer = movieTrailers.get(adapterPosition);
videoOnClickHandler.onClick(movieTrailer);
}
}
#NonNull
#Override
public VideoAdapterViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
Context context = viewGroup.getContext();
int gridItem = R.layout.movie_trailer;
LayoutInflater inflater = LayoutInflater.from(context);
boolean shouldAttachToParentImmediately = false;
View view = inflater.inflate(gridItem, viewGroup,shouldAttachToParentImmediately);
return new VideoAdapter.VideoAdapterViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull VideoAdapterViewHolder videoAdapterViewHolder, int i) {
MovieTrailer movieTrailer = movieTrailers.get(i);
videoAdapterViewHolder.videoTypeText.setText(movieTrailer.getType());
videoAdapterViewHolder.videoNameText.setText(movieTrailer.getName());
}
#Override
public int getItemCount() {
if (null == movieTrailers) return 0;
return movieTrailers.size();
}
//Function to set movieTrailers
public void setMovieTrailerArray(List<MovieTrailer> trailerArrayToSet){
movieTrailers = trailerArrayToSet;
notifyDataSetChanged();
}
}
The Interface:
public interface GetDataService {
#GET("{path}?api_key=" + BuildConfig.API_KEY)
Call<MoviesList> getAllMovies(#Path("path") String path);
#GET("{movieId}/reviews?api_key=" + BuildConfig.API_KEY)
Call<TrailersList> getAllTrailers(#Path("movieId") String movieId);
#GET("{movieId}/videos?api_key=" + BuildConfig.API_KEY)
Call<ReviewsList> getAllReviews(#Path("movieId") String movieId);
}
The Retrofit Instance:
public class RetrofitClientInstance {
//Base URL for API request
private static final String MOVIE_DATABASE_URL_POPULAR =
"http://api.themoviedb.org/3/movie/";
/**
* Get Retrofit Instance
*/
private static Retrofit getRetrofitInstance() {
return new Retrofit.Builder()
.baseUrl(MOVIE_DATABASE_URL_POPULAR)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
/**
* Get API Service
*
* #return API Service
*/
public static GetDataService getApiService() {
return getRetrofitInstance().create(GetDataService.class);
}
}
And the method from the DetailsActivity:
private void loadMovieTrailers(String movieId){
GetDataService api = RetrofitClientInstance.getApiService();
Call<TrailersList> call = api.getAllTrailers(movieId);
call.enqueue(new Callback<TrailersList>() {
#Override
public void onResponse(Call<TrailersList> call, Response<TrailersList> response) {
if(response.isSuccessful()){
movieTrailers = response.body().getTrailers();
if(movieTrailers.get(0).getName() == null){
Log.d("MODEL", "Null");
}else {
Log.d("MODEL", "Not Null");
}
videoAdapter.setMovieTrailerArray(movieTrailers);
}
}
#Override
public void onFailure(Call<TrailersList> call, Throwable t) {
}
});
}
Someone has an idea where the mistake is?
I think the problem is in your interface class with these methods,
#GET("{movieId}/reviews?api_key=" + BuildConfig.API_KEY)
Call<TrailersList> getAllTrailers(#Path("movieId") String movieId);
#GET("{movieId}/videos?api_key=" + BuildConfig.API_KEY)
Call<ReviewsList> getAllReviews(#Path("movieId") String movieId);
From {movieId}/reviews you'll get the following JSON response,
{
"id": 297761,
"page": 1,
"results": [
{
"id": "57a814dc9251415cfb00309a",
"author": "Frank Ochieng",
"content": "Summertime 2016 has not been very kind to DC Comics-based personalities looking to shine consistently like their big screen Marvel Comics counterparts.",
"url": "https://www.themoviedb.org/review/57a814dc9251415cfb00309a"
}
],
"total_pages": 1,
"total_results": 1
}
and {movieId}/videos returns,
{
"id": 550,
"results": [
{
"id": "533ec654c3a36854480003eb",
"iso_639_1": "en",
"iso_3166_1": "US",
"key": "SUXWAEX2jlg",
"name": "Trailer 1",
"site": "YouTube",
"size": 720,
"type": "Trailer"
}
]
}
So, both of them returns almost same result with JSONArray (results) enclosed withing JSONObject. JSON response is proper there's no problem at all.
While parsing JSON response, Gson converter factory fails to find the equivalent POJO class for the response. You don't even get any errors because both are returning same type response.
A simple fix is to change (inter change) the URLs of the following methods.
#GET("{movieId}/videos?api_key=" + BuildConfig.API_KEY) // change from reviews to videos
Call<TrailersList> getAllTrailers(#Path("movieId") String movieId);
#GET("{movieId}/reviews?api_key=" + BuildConfig.API_KEY) // change from videos to reviews
Call<ReviewsList> getAllReviews(#Path("movieId") String movieId);
That's it!
In your MovieTrailer class, the #Expose annotations are missing for the fields. Thus, Gson creates the objects, but doesn't find any fields to put the actual data in.
Btw. The #SerializedFieldName is only needed if the field name in the JSON is different than the field name in your model.

how to display in dashboard_image_details in next intent

my json how to display in dashboard_image_details in intent
retrofit 2 how to display in recyclerview
{
"dashboard_info": [
{
"id": "1",
"week_id": "1",
"week_name": "week one",
"color": "#9a94c7",
"week_title": "Fruits",
"password": "admin1",
"week_image": "http://192.168.0.2/littlezebra/school_uploads/week_images/1/fruit.png",
"dashboard_image_details": [
{
"id": "6",
"image_title": "Apple",
"image": "http://192.168.0.2/littlezebra/school_uploads/dashboard_images/1/6/app.png",
"color": "#c88dac"
},
]
}
}
You might want like:
Fruit
Apple Banana etc
(View like play store vertical scroll(Category like fruits) and horizontal scroll(items like Apple))
So your first adapter showing dashboard_info
Then need to add list or recyclerview inside first adapter xml file.(for dashboard_image_details )
And then need to call second adapter from first adapters
public View getView(int position, View convertView, ViewGroup parent){} method.
Second adapter will be normal just with recyclerview with horizontal scroll.
public class dashboard {
#SerializedName("dashboard_info")
#Expose
private ArrayList<dash> list;
public ArrayList<dash> getList() {
return list;
}
public void setList(ArrayList<dash> list) {
this.list = list;
}
}
create another class for dashboard details
public class dash {
#SerializedName("week_title")
#Expose
private String name ;
#SerializedName("password")
#Expose
private String email;
#SerializedName("dashboard_image_details")
private ArrayList<image> list;
public ArrayList<image> getList() {
return list;
}
public void setList(ArrayList<image> list) {
this.list = list;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
I have used the listview with base adapter code in getview method is below
dash em = model.get(i);
txtemail.setText(em.getEmail());
image img = em.getList().get(0);
txtname.setText(em.getName() + img.getImgtitle());
If having doubts then go ahead...

Android , Deserialize JSON Array that have different types using Jackson

I have an Android application that uses Jackson to deserialize the data and I face troubles in creating the pojo for this json string:
{
"response": [{
"view": "ticker",
"items": []
}, {
"view": "note",
"note": "This is a note"
}, {
"wn": "bla",
"sd": "bla bla",
"tf": 28,
"rh": 22,
"ws": 9,
"ti": "14:00",
"view": "hbhi"
}]
}
I create the following pojos:
TickerModel.java
public class TickerModel implements Serializable {
#JsonProperty("view")
private String view ;
#JsonProperty("items")
private String items;
public String getView() {
return view;
}
public void setView(String view) {
this.view = view;
}
public String getItems() {
return items;
}
public void setItems(String items) {
this.items = items;
}
}
NoteModel.java
public class NoteModel implements Serializable {
#JsonProperty("view")
private String view ;
#JsonProperty("note")
private String note;
public String getView() {
return view;
}
public void setView(String view) {
this.view = view;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
}
any ideas on how to to do deserialize this JSON using Jackson?
first validate json using this.
And create pojo classes using this or this
No need to create two separate pojo's, you can have pojo like below -
public class Response {
#JsonProperty("view")
private String view;
#JsonProperty("items")
private List<Object> items = new ArrayList<Object>();
#JsonProperty("note")
private String note;
#JsonProperty("wn")
private String wn;
#JsonProperty("sd")
private String sd;
#JsonProperty("tf")
private Integer tf;
#JsonProperty("rh")
private Integer rh;
#JsonProperty("ws")
private Integer ws;
#JsonProperty("ti")
private String ti;
//setters //getters
}
Note: Since items is an array in your json, you should map it with array-list of type objects. Also you can get pojo's craeted online if you have json data - http://www.jsonschema2pojo.org/

Resources