How i can parsing json object with retrofit and recyclerView - java

I'm using GitHub API to show in my application the most starred repository and their names and avatar and description in recyclerView but when I lunch the app everything working but the avatar_url and login return Null.
this is a JSON from Github API
https://api.github.com/search/repositories?q=created:%3E2019-10-01&sort=stars&order=desc
I tried this :
client class:
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class Client {
public static final String BASE_URL="https://api.github.com";
public static Retrofit retrofit=null;
public static Retrofit getClient()
{
if(retrofit==null)
{
retrofit=new Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create()).build();
}
return retrofit;
}
}
Service Class:
package com.example.gethubapi.api;
import com.example.gethubapi.model.ItemResponse;
import retrofit2.Call;
import retrofit2.http.GET;
public interface Service {
#GET("/search/repositories?q=created:>2017-10-22&sort=stars&order=desc&page=2")
Call<ItemResponse> getItems();
}
Item class
here is the problem if u checked the jSON file in link above you will find a child object from item called owner and i cant select the name of avatar_url and owner name directly
import com.google.gson.annotations.SerializedName;
public class Item {
#SerializedName("avatar_url")
#Expose
private String avatarUrl;
#SerializedName("name")
#Expose
private String name;
#SerializedName("description")
#Expose
private String description;
#SerializedName("login")
#Expose
private String owner;
#SerializedName("stargazers_count")
#Expose
private int stargazers;
public Item(String avatar_url,String name,String description,String owner,int stargazers )
{
this.avatarUrl=avatar_url;
this.name=name;
this.description=description;
this.owner=owner;
this.stargazers=stargazers;
}
public String getAvatarUrl()
{
return avatarUrl;
}
public String getName()
{
return name;
}
public String getDescription()
{
return description;
}
public String getOwner()
{
return owner;
}
public int getStargazers()
{
return stargazers;
}
}

Looking at the JSON response, the Owner object is part of the Item object. meaning it's nested in the Item object.
public class Owner {
#SerializedName("avatar_url")
#Expose
private String avatarUrl;
#SerializedName("login")
#Expose
private String login;
public Owner(){}
public void setAvatarUrl(String avatar_URL){
this.avatarUrl = avatar_URL;
}
pubic String getAvatarUrl(){
return avatarUrl;
}
public String getLogin(){
return login;
}
public void setLogin(String login){
this.login = login;}
}
public class Item {
#SerializedName("name")
#Expose
private String name;
#SerializedName("description")
#Expose
private String description;
#SerializedName("owner")
#Expose
private Owner owner;
#SerializedName("stargazers_count")
#Expose
private int stargazers;
.........
}

Since the login and avatar_url is under owner object.
You need to create a separate class for owner object , just like you did for a single item.
And don't forget to mention the object class in your Item class.

In my case the stargazer spelling was wrong, just correct the spelling
example:- from
stargazer_count
to
stargazers_count.

Related

How to model Json array in Java?

I am pretty new to Java.
I want to model this request for a batch request to Microsoft graphAPI.
{"requests":[
{"id":"employeeId","method":"GET","url":"/me/employeeId"},
{"id":"thumbnailPhoto","method":"GET","url":"/me/photo/$value"}]
}
So "requests" is an array of BatchRequest object.
What I have currently:
// BatchRequest object
public class BatchRequest
{
private String id;
private String method;
private String url;
public BatchRequest(String id, String method, String url)
{
this.id = id;
this.method = method;
this.url = url;
}
// getters and setters below
}
private List<BatchRequest> requests;
#Override
public UserInfoResponse callGraphApi()
{
BatchRequest employeeId = new BatchRequest("employeeId", "GET", "/me/employeeId");
BatchRequest photo = new BatchRequest("thumbnailPhoto", "GET", "/me/photo/$value");
requests.add(employeeId);
requests.add(photo);
return callGraphApi(requests);
}
Is this how I would model the JSON?
Found this Jsonschema2pojo while i was trying to figure out how to model my Json response into java objects in android app development. Install gson or jackson in your project and it'll take care of the things under the hood.
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class BatchRequest {
#SerializedName("requests")
#Expose
private List<Request> requests = null;
public List<Request> getRequests() {
return requests;
}
public void setRequests(List<Request> requests) {
this.requests = requests;
}
}
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Request {
#SerializedName("id")
#Expose
private String id;
#SerializedName("method")
#Expose
private String method;
#SerializedName("url")
#Expose
private String url;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
Sure. The task of turning an instance of a simple java object into a bunch of JSON, as well as the job of turning a bunch of JSON, combined with a list of simple java classes into instances of those classes, is called 'marshalling'. You'll need a library to do it; the popular ones are Jackson and GSON.

I'm passing a list of JSON file is not getting display in the Android application

I was Passing a this JSON http://www.mocky.io/v2/5cacde192f000078003a93bb
i was trying to print a just a category_name
I'm not able to get the data list , when i pass the object with out the data list just like http://www.mocky.io/v2/5cb859344c0000092ed3d4df
private Category_name category_name;
public Category_name getCategoryName() {
return category_name;
}
}
public class Category_name {
#SerializedName("category_name")
public String name;
public String getName() {
return name;
}
}````
i can access that through the NewAdapter.java
with the following code
#Override
public void onBindViewHolder(NewsViewHolder holder, int position) {
Log.e("Its coming","NewAdapter");
ApiObject apiObject = apiObjectList.get(position);
holder.title.setText(apiObject.getCategoryName().getName());
}
with the same code I'm not able to get the data list
#SerializedName("data")
public List<Data> data;
public List<Data> getData() {
return data;
}
public class Data {
#SerializedName("details")
private Category_name category_name;
public Category_name getCategoryName() {
return category_name;
}
}
public class Category_name {
#SerializedName("category_name")
public String name;
public String getName() {
return name;
}
}
#Override
public void onBindViewHolder(NewsViewHolder holder, int position) {
Log.e("Its coming","NewAdapter");
ApiObject apiObject = apiObjectList.get(position);
holder.title.setText(apiObject.getData().getCategoryName().getName());
}
I'm not able to access the getCategoryName();
Please help thanks in advance
use json 2 pojo conversion to create proper model class of json data
http://www.jsonschema2pojo.org/
pass whole example object to adapter constructer.
I think you need to follow these way of POJO parsing according to your JSON response.
public class Data{
#Serialization("status")
#Expose
private String status;
#Serialization("data")
#Expose
private List<MyData> data;
Then
public class MyData{
#Serialization("details")
#Expose
private List<Details> getDetails();
#Serialization("product_count")
#Expose
private String Product_count;
#Serialization("products")
#Expose
private List<Products> getProducts();
//setter and getters
}
Details POJO
Public class Details{
#Serialization("category_id")
#Expose
private String category_id;
#Serialization("category_name")
#Expose
private String category_name;
#Serialization("category_icon")
#Expose
private String category_icon;
//setter and getters
}
Products POJO
Public class Products{
#Serialization("product_id")
#Expose
private String product_id;
#Serialization("product_name")
#Expose
private String product_name;
#Serialization("product_image")
#Expose
private String product_icon;
etc
//setter and getters
}

How to add array list to rest API request using Rest Assured?

I'm using rest assured for Rest api testing with the help of POJO classes like getter and setter methods to set the values but i'm stuck with array list in between rest request,please any one provide proper code to get exact below request to post using rest assured.
Request:
{
"firstName":"SuryaNAMASKARAM",
"lastName":"mangalam",
"mobileNo" :4954758490,
"emailId" :"surya.mangalam#futureretail.in",
"houseNoStreet":"123456",
"buildingName":"",
"landmark":"Nirmala jathara",
"paymentDetail" :
[{"paymentType":"CASH","No":"3519000012","Date":"16-06-2018","amount":"100.00"}]
}
CustomerCreate Class:
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("firstName")
#Expose
private String firstName;
#SerializedName("lastName")
#Expose
private String lastName;
#SerializedName("mobileNo")
#Expose
private Integer mobileNo;
#SerializedName("emailId")
#Expose
private String emailId;
#SerializedName("houseNoStreet")
#Expose
private String houseNoStreet;
#SerializedName("buildingName")
#Expose
private String buildingName;
#SerializedName("landmark")
#Expose
private String landmark;
#SerializedName("paymentDetail")
#Expose
private List<PaymentDetail> paymentDetail = null;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Integer getMobileNo() {
return mobileNo;
}
public void setMobileNo(Integer mobileNo) {
this.mobileNo = mobileNo;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public String getHouseNoStreet() {
return houseNoStreet;
}
public void setHouseNoStreet(String houseNoStreet) {
this.houseNoStreet = houseNoStreet;
}
public String getBuildingName() {
return buildingName;
}
public void setBuildingName(String buildingName) {
this.buildingName = buildingName;
}
public String getLandmark() {
return landmark;
}
public void setLandmark(String landmark) {
this.landmark = landmark;
}
public List<PaymentDetail> getPaymentDetail() {
return paymentDetail;
}
public void setPaymentDetail(List<PaymentDetail> paymentDetail) {
this.paymentDetail = paymentDetail;
}
}
PaymentDetails:
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class PaymentDetail {
#SerializedName("paymentType")
#Expose
private String paymentType;
#SerializedName("No")
#Expose
private String no;
#SerializedName("Date")
#Expose
private String date;
#SerializedName("amount")
#Expose
private String amount;
public String getPaymentType() {
return paymentType;
}
public void setPaymentType(String paymentType) {
this.paymentType = paymentType;
}
public String getNo() {
return no;
}
public void setNo(String no) {
this.no = no;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
}
Test Class:
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.test.requestpojo.Example;
import com.test.requestpojo.PaymentDetail;
public class TestAPI {
public void setTestData() throws JSONException {
Example example = new Example();
example.setFirstName("Rajesh");
example.setLastName("Kuchana");
example.setMobileNo("3434343434");
example.setEmailId("rajesh.kuchana#futureretail.in");
example.setDateOfBirth("10-10-2018");
example.setGender(1);
example.setHouseNoStreet("Test");
example.setBuildingName("Test");
example.setLandmark("Test");
List<PaymentDetail> data = new ArrayList<PaymentDetail>();
PaymentDetail paymentDetail = new PaymentDetail();
paymentDetail.setAmount("999.00");
data.add(paymentDetail);
JSONObject jsonObject = new JSONObject(example);
JSONArray jsonArray = new JSONArray(data);
jsonArray.put(data);
System.out.println(jsonArray.put(data));
}
In your test class, what you must do is separate the test data creation to a different class and pass that as data provider to your test method. This is from design point of view.
Coming to your problem:
You are already using gson, why are you constructing a JSONObject. Instead do something like below;
Gson gson = new Gson();
String _my_obj = gson.toJson(example);
Hope this is what you are looking for.

Access JSON value called "class" with Gson

I am trying to get the value of class in the following JSON:
{
"battlegroup": "Misery",
"class": 1,
"race": 4,
"gender": 0
}
I access the other fields (battlegroup, race etc.) with:
WoWDetails info = gson.fromJson(response, WoWDetails.class);
raceID = info.race;
WoWDetails is as following:
class WoWDetails {
// character details
public String battlegroup;
public Integer achievementPoints;
public Integer race;
public Integer class;
}
But if I try WoWDetails.class it's giving me an error saying "Unknown class: info". Which makes sense because info is not a class.
Is there a way around this? Can I escape the word "class" in any way possible?
The name class is not editable, since it's not my API.
You can map the class field to JSON key using #SerializedName
WowDetails.java
public class WoWDetails {
String battlegroup;
#SerializedName("class")
int className;
int race;
int gender;
}
Set your Package name
package com.nonprofit.nonprofit;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class WoWDetails {
#SerializedName("battlegroup")
#Expose
private String battlegroup;
#SerializedName("class")
#Expose
private Integer _class;
#SerializedName("race")
#Expose
private Integer race;
#SerializedName("gender")
#Expose
private Integer gender;
public String getBattlegroup() {
return battlegroup;
}
public void setBattlegroup(String battlegroup) {
this.battlegroup = battlegroup;
}
public Integer getClass_() {
return _class;
}
public void setClass_(Integer _class) {
this._class = _class;
}
public Integer getRace() {
return race;
}
public void setRace(Integer race) {
this.race = race;
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
}
You can get your details like below
WoWDetails info = gson.fromJson(response, WoWDetails.class);
info.getGender();
info.getRace();

Save and retrieve Arraylists using ActiveAndroid ORM and Retrofit

I am using Retrofit and ActiveAndroid ORM in my application. I have the following Model class:
#Table(name = "formresource")
public class FormResource extends Model implements Serializable{
#Column(name="name")
#SerializedName("name")
#Expose
private String name;
#Column
#SerializedName("resources")
#Expose
private List<FormResource> resources = new ArrayList<FormResource>();
#Column(name = "valueReference")
#SerializedName("valueReference")
#Expose
private String valueReference;
#Column(name = "uuid")
#SerializedName("uuid")
#Expose
private String uuid;
#Column(name = "display")
#SerializedName("display")
#Expose
private String display;
#Column(name = "links")
#SerializedName("links")
#Expose
private List<Link> links = new ArrayList<Link>();
public FormResource()
{
super();
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public String getDisplay() {
return display;
}
public void setDisplay(String display) {
this.display = display;
}
public List<Link> getLinks() {
return links;
}
public void setLinks(List<Link> links) {
this.links = links;
}
public String getValueReference() {
return valueReference;
}
public void setValueReference(String valueReference) {
this.valueReference = valueReference;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<FormResource> getResources() {
return resources;
}
public void setResources(List<FormResource> resources) {
this.resources = resources;
}
}
Now, I obtain the Formresources once while starting the application and save it. Then in another activity I use the saved formresources to populate a listview. This much works fine. Now, I want to access the nested formresources like this:
formresourcelist.get(position).getResources();
This always returns a blank list of List<FormResource> . What should I do to properly save and retrieve this list? I need to maintain compatibility with Retrofit at the same time.
I think I found a workaround. I made the following changes in the Model Class:
#Table(name = "formresource")
public class FormResource extends Model implements Serializable{
Gson gson=new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
Type formresourcelistType = new TypeToken<List<FormResource>>(){}.getType();
#SerializedName("resources")
#Expose
private List<FormResource> resources = new ArrayList<FormResource>();
#Column(name = "resources")
#Expose
private String resourcelist;
public List<FormResource> getResources() {
return resources;
}
public void setResources(List<FormResource> resources) {
this.resources = resources;
}
public void setResourcelist()
{
this.resourcelist=gson.toJson(resources,formresourcelistType);
}
public List<FormResource> getResourceList() {
List<FormResource> resourceList=gson.fromJson(this.resourcelist,formresourcelistType);
return resourceList;
}
}
Basically I am serializing the ArrayList and persisting it as a String in the DB. While saving a FormResource, I do the following:
formresourceObject.setResourcelist();
formresourceObject.save();
Since you're using Retrofit to populate the FormResource data, you should not initialize any fields inside the model.
This line is the problem :
private List<FormResource> resources = new ArrayList<FormResource>();
try removing the initialization and just declare the field like :
private List<FormResource> resources;
and then try calling formresourcelist.get(position).getResources();
Good luck!

Categories

Resources