Retrofit 2 Json Response Json Array and Object

Parse JSON array response using Retrofit & Gson

Please try to use this one

    @FormUrlEncoded
@POST("api/sponsors")
Call<List<SponsorsResult>> getStatesAndDistrict(
@Field("xyz") String field1
);



Call <List<SponsorsResult>> call = service.getSponsorsValue();

call.enqueue(new Callback<List<SponsorsResult>>() {
@Override
public void onResponse(Call<List<SponsorsResult>> call, Response<List<SponsorsResult>> response) {

List<SponsorsResult> rs = response.body();

}

@Override
public void onFailure(Call<List<SponsorsResult>> call, Throwable t) {

}
});



class SponsorsResult {

@SerializedName("sponsors")
private List<SponsorsValue> sponsors;

public List<SponsorsValue> getSponsors() {
return sponsors;
}
}

class SponsorsValue{
@SerializedName("leg_id")
@Expose
private String legId;
@SerializedName("type")
@Expose
private String type;
@SerializedName("name")
@Expose
private String name;

public String getLegId() {
return legId;
}

public void setLegId(String legId) {
this.legId = legId;
}

public String getType() {
return type;
}

public void setType(String type) {
this.type = type;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

}

Please let me know if you are facing any issue.

How to parse json array of objects inside object using Retrofit

Try to use next class in response object:

data class PokedexResponse (
@SerializedName("pokemon")
val pokemons: List<Post>
)

interface SimpleApi {
@GET("pokedex.json")
suspend fun getCustomPosts(): Response<PokedexResponse>
}

My guess is that you missed to parse pokemon object:

{
"pokemon": [{ ... }]
}

how to store json array response using retrofit

In MainActivity.java file, update the code as below as you are printing rs object in your toast message, it prints only the object address not the value in it. So to print the value of the object you received, you must call the methods of the object to get value like as.

MainActivity.java

private void LoginRetrofit(String user_name) {  
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("url")
.addConverterFactory(GsonConverterFactory.create())
.build();

...
call.enqueue(new Callback<List<Task>>() {
@Override
public void onResponse(Call<List<Task>> call, Response<List<Task>> response) {
try {
List<Task> rs=response.body();
if(rs.size() > 0){
Task user = rs.get(0);
String id = user.getId();
String location = user.getLocation();
Toast.makeText(getApplicationContext(),"Response : Id="+id+" and location="+location, Toast.LENGTH_LONG).show();
}

}
catch (Exception e)
{
Log.d("REsponse error",e.getMessage());
}
}

...
});
}

and update the Task model as

Task.java

public class Task { 
@SerializedName("id") public String id;
@SerializedName("date") public String date;
@SerializedName("location") public String location;
@SerializedName("img") public String img;

public Task(String id, String date, String location, String img) {
this.id=id;
this.date=date;
this.location=location;
this.img=img;
}

public String getId(){ return this.id; }
public String getDate(){ return this.date; }
public String getLocation(){ return this.location; }
public String getImg(){ return this.img; }
}

Parse Json array with multiple objects using retrofit 2 in android

Your Json key value data is changing from one index to another.

Wrong Json:

[{
//Make this either integer or boolean
"rank": 1,
// best rate is object here in the next index, it's treated as boolean.
"best_rate": {
"id_asset": "1",
"value": "5000",
"loan_to_value": "50",
"offered": "2500",
"annual_rate": "3",
"quantity": "5",
"rank": "1"
}

},
{
"rank":false,
"best_rate":false,
}
]

I have a complete project shared on github with your json.
https://github.com/lingarajsankaravelu/retrofit2v.git

Retrofit code should be like this as i mentioned in the question comment.

@GET("url")
Call<List<AssetResponse>> getAssetList();

As you have requested to explain the changes in your pojo class it should be like this.

AssetReponse.class:

public class AssetResponse {
private Integer id_asset;
private Integer id_category;
private Integer id_brand;
private String name;
private Integer status;
private String updated_at;

private AssetRate assetRate;
private AssetCategory assetCategory;
private Links links;
private Self self;
private AssetBrand assetBrand;
private HasLinked hasLinked;


public Integer getId_asset() {
return id_asset;
}

public void setId_asset(Integer id_asset) {
this.id_asset = id_asset;
}

public Integer getId_category() {
return id_category;
}

public void setId_category(Integer id_category) {
this.id_category = id_category;
}

public Integer getId_brand() {
return id_brand;
}

public void setId_brand(Integer id_brand) {
this.id_brand = id_brand;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Integer getStatus() {
return status;
}

public void setStatus(Integer status) {
this.status = status;
}

public String getUpdated_at() {
return updated_at;
}

public void setUpdated_at(String updated_at) {
this.updated_at = updated_at;
}

public AssetRate getAssetRate() {
return assetRate;
}

public void setAssetRate(AssetRate assetRate) {
this.assetRate = assetRate;
}

public AssetCategory getAssetCategory() {
return assetCategory;
}

public void setAssetCategory(AssetCategory assetCategory) {
this.assetCategory = assetCategory;
}

public Links getLinks() {
return links;
}

public void setLinks(Links links) {
this.links = links;
}

public Self getSelf() {
return self;
}

public void setSelf(Self self) {
this.self = self;
}

public AssetBrand getAssetBrand() {
return assetBrand;
}

public void setAssetBrand(AssetBrand assetBrand) {
this.assetBrand = assetBrand;
}

public HasLinked getHasLinked() {
return hasLinked;
}

public void setHasLinked(HasLinked hasLinked) {
this.hasLinked = hasLinked;
}
}

AssetRate.class

public class AssetRate {

private Integer id_asset_rate;
private Integer id_asset;
private Double value;
private Double loan_to_value;
private Double offered;
private Double annual_rate;
private String updated_at;

public Integer getId_asset_rate() {
return id_asset_rate;
}

public void setId_asset_rate(Integer id_asset_rate) {
this.id_asset_rate = id_asset_rate;
}

public Integer getId_asset() {
return id_asset;
}

public void setId_asset(Integer id_asset) {
this.id_asset = id_asset;
}

public Double getValue() {
return value;
}

public void setValue(Double value) {
this.value = value;
}

public Double getLoan_to_value() {
return loan_to_value;
}

public void setLoan_to_value(Double loan_to_value) {
this.loan_to_value = loan_to_value;
}

public Double getOffered() {
return offered;
}

public void setOffered(Double offered) {
this.offered = offered;
}

public Double getAnnual_rate() {
return annual_rate;
}

public void setAnnual_rate(Double annual_rate) {
this.annual_rate = annual_rate;
}

public String getUpdated_at() {
return updated_at;
}

public void setUpdated_at(String updated_at) {
this.updated_at = updated_at;
}
}

Seperate your inner class like above. Seperating your inner class model will be useful if you are working on a large project. where you don't have to write the same pojo class again. you can use this seperate class structure instead.

How to receive a Json array (result) with retrofit2

After a lot of testing guided by the 3 answers given and some video tutorial I finally figure it out.

ApiClient:

public class ApiClient {

private static final String BASE_URL="http://192.168.31.206/";
public static Retrofit retrofit = null;
public static ApiInterface instance=null;

public static Retrofit getApiClient(){

if (retrofit==null){
retrofit=new Retrofit.Builder().baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create()).build();
}
return retrofit;
}

public static ApiInterface getInterface(){

if (instance==null){
instance=getApiClient().create(ApiInterface.class);
}


return instance;
}

}

ApiInterface:

public interface ApiInterface {

//this could be test1_database/getAllUser.json
@GET("test1_database/getAllUser.php")
Call<Result> getWorkers();


}

Workers (POJO) class:

public class Workers {


@SerializedName("userid")
private String userid;
@SerializedName("username")
private String username;
@SerializedName("job")
private String job;
@SerializedName("age")
private String age;

public String getUserid() {
return userid;
}

public void setUserid(String userid) {
this.userid = userid;
}

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public String getJob() {
return job;
}

public void setJob(String job) {
this.job = job;
}

public String getAge() {
return age;
}

public void setAge(String age) {
this.age = age;
}

}

Result (POJO) class:

public class Result {

@SerializedName("result")
private List<Workers> result = null;

public List<Workers> getResult() {
return result;
}

public void setResult(List<Workers> result) {
this.result = result;
}

}

MainActivity class:

public class MainActivity extends AppCompatActivity {

RecyclerView recyclerView;
List<Workers> list = new ArrayList<>();
WorkerAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

recyclerView = findViewById(R.id.recycler);
recyclerView.setHasFixedSize(true);
LinearLayoutManager manager = new LinearLayoutManager(this);
manager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(manager);

ApiInterface apiCall = ApiClient.getInterface();
Call<Result> call = apiCall.getWorkers();

call.enqueue(new Callback<Result>() {
@Override
public void onResponse(Call<Result> call, Response<Result> response) {
list = response.body().getResult();
adapter = new WorkerAdapter(MainActivity.this,list);
recyclerView.setAdapter(adapter);
}

@Override
public void onFailure(Call<Result> call, Throwable t) {

}
});

}}

I am Showing the results in a recyclerview using this adapter:

public class WorkerAdapter extends RecyclerView.Adapter<WorkerAdapter.ViewHolder>{
Context context;
List<Workers> list;

public WorkerAdapter(Context context,List<Workers> list) {
this.context = context;
this.list = list;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.item_recycler,parent,false);
ViewHolder holder = new ViewHolder(v);
return holder;
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {

holder.id.setText(String.valueOf(list.get(position).getUserid()));
holder.name.setText(list.get(position).getUsername());
holder.job.setText(list.get(position).getJob());
holder.age.setText(String.valueOf(list.get(position).getAge()));
}

@Override
public int getItemCount() {
return list.size();
}


public class ViewHolder extends RecyclerView.ViewHolder {

TextView name, job, age,id;

public ViewHolder(View itemView) {
super(itemView);
id = (TextView) itemView.findViewById(R.id.idtxt);
name= (TextView) itemView.findViewById(R.id.nametxt);
job=(TextView) itemView.findViewById(R.id.jobtxt);
age=(TextView) itemView.findViewById(R.id.agetxt);
}
}
}

Thanks everyone for your help!

Retrofit Response with dynamic JSON array names

in that case you can use JSONObject for getting dynamic value just convert retrofit response to JSONObject for that you have to change response type of retrofit Call

Call<ResponseBody> call = exampleApi();

call.enqueue(new Callback<ResponseBody>() {

@Override
public void onResponse(Response<ResponseBody> response, Retrofit retrofit) {
String result = response.body().string();
JSONObject object = new JSONObject(result);

// can get any value from keys
// for example in your case
JSONArray array1 = object.getJSONObject('all').getJSONArray('loc1');
//similarly just change key to loc2 and so on

JSONArray array2 = object.getJSONObject('all').getJSONArray('loc2');

}

@Override
public void onFailure(Throwable t) {

}
});

How to parse JSON response Array of object, where array is without key name

Create One Class Like,

class Test {

public List<TestValue> testValues;
}

Then call API,

Call<List<Test>> getTestData(@Field("xyz") String field1);


Call <List<Test>> call = service.getTestData("val");

call.enqueue(new Callback<List<Test>>() {
@Override
public void onResponse(Call<List<Test>> call, Response<List<Test>>
response) {

List<Test> rs = response.body();

}

@Override
public void onFailure(Call<List<Test>> call, Throwable t) {

}
});

User Your Model class, this is only for example purpose.



Related Topics



Leave a reply



Submit