I'm working on project in which I have to implement on API. This API repsonse is objects of ArrayList. Can you please help me with creating its POJO class and if possible its implementation. I'm using retrofit2 & GSON.
As shown in following JSON schema, brand names will be added in brandsonly by admin, and it will be added in allorders as a arraylist which have multiple sub-objects.
Like, if admin add Redmi in the brandsonly then it will create Redmi[] in the allorders
{
"status": "success",
"brandsonly": [
{
"_id": "",
"brandname": "SAMSUNG",
},
{
"_id": "",
"brandname": "VIVO",
},
{
"_id": "",
"brandname": "NOKIA"
},
{
"_id": "",
"brandname": "IPHONE",
}
],
"allorders": {
"SAMSUNG": [],
"VIVO": [],
"NOKIA": [],
"IPHONE": [
{
"_id": "",
"order_id": "",
"__v": 0,
"adminconfirmation": 1,
"finalpricetodeduct": 30950
},
{
"_id": "",
"order_id": "",
"__v": 0,
"adminconfirmation": 1,
"finalpricetodeduct":
}
]
},
}
My Retrofit call from activity:
final AllOrdersResponse allOrdersResponse = new AllOrdersResponse(userID);
Call<AllOrdersResponse> responseCall = retrofit_interface.allOrderResponse(allOrdersResponse, "Bearer " + AuthToken);
responseCall.enqueue(new Callback<AllOrdersResponse>() {
#Override
public void onResponse(#NotNull Call<AllOrdersResponse> call, #NotNull Response<AllOrdersResponse> response) {
AllOrdersResponse response1 = response.body();
}
#Override
public void onFailure(#NotNull Call<AllOrdersResponse> call, #NotNull Throwable t) {
if (t instanceof SocketTimeoutException)
Toast.makeText(context, "Socket Time out. Please try again.", Toast.LENGTH_LONG).show();
else
Toast.makeText(context, t.toString(), Toast.LENGTH_LONG).show();
}
});
I dont think a POJO schema would work in this instance as it will always change. It would be much better is the allorders was the same as brandsonly a JSON Array of JSON Array
However, if that cannot be changed have a look at the below.
final AllOrdersResponse allOrdersResponse = new AllOrdersResponse(userID);
Call<AllOrdersResponse> responseCall = retrofit_interface.allOrderResponse(allOrdersResponse, "Bearer " + AuthToken);
responseCall.enqueue(new Callback<AllOrdersResponse>() {
#Override
public void onResponse(#NotNull Call<AllOrdersResponse> call, #NotNull Response<AllOrdersResponse> response) {
AllOrdersResponse response1 = response.body();
List<String> brands = new ArrayList<>();
List<Map<String, Product>> products = new ArrayList<>();
JSONObject jsonObject = new JSONObject(response1);
for(JSONObject brand : jsonObject.get("brandsonly")){
brands.add(brand.getvalue("brandname"));
}
if(brands.size= > 0){
for(String brandname: brands){
HashMap<String, Product> tempHash = new HashMap<>();
JSONArray temp = jsonObject.getJSONArray(brandname);
foreach(JSONObject x : temp){
Product product = new Product();
product.FromJSONObject(x);
temp.put(brandname, product);
}
products.add(tempHash);
}
}
}
#Override
public void onFailure(#NotNull Call<AllOrdersResponse> call, #NotNull Throwable t) {
if (t instanceof SocketTimeoutException)
Toast.makeText(context, "Socket Time out. Please try again.", Toast.LENGTH_LONG).show();
else
Toast.makeText(context, t.toString(), Toast.LENGTH_LONG).show();
}
});
So you have a list of BandNames with a value of each product.
I would also recommend looking at jsonschema2.pojo
I am getting response from API as a JSONarray and I can get the data into my arraymodel but the problem is I need some specific data from one array and I don't have any idea how to do that.
the array is:
"history": [
{
"id": "20",
"code": "mcw_5b97de588ce0c",
"date": "2018-09-11 17:25:12",
"status": "1",
"name": "a:1:{s:7:\"english\";s:9:\"rent bill\";}",
"img": "shop.png"
}
I want the English, S:9 and the rent bill data from name.
I am posting my code here so you can understand what I have done and what mistake i'm committing.
public void shopListing()
{
showSimpleProgressDialog(this, "Loading...","Fetching Shops History",false);
StringRequest stringRequest = new StringRequest(Request.Method.POST, shopurl,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("strrrrr", ">>" + response);
try {
JSONObject obj = new JSONObject(response);
//if(obj.optString("status").equals("true")){
dataModelArrayList = new ArrayList<>();
JSONArray dataArray = obj.getJSONArray("history");
for (int i = 0; i < dataArray.length(); i++) {
shopModel playerModel = new shopModel();
JSONObject dataobj = dataArray.getJSONObject(i);
playerModel.setId(dataobj.getString("id"));
playerModel.setName(dataobj.getString("name"));
playerModel.setDetails(dataobj.getString("date"));
dataModelArrayList.add(playerModel);
}
setupListview();
// }
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//displaying the error in toast if occurrs
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
String api = getApi_key();
String user = getUser_key();
Map<String, String> param = new HashMap<> ();
param.put("api_key", api);
param.put("user_key", user);
return param;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
Your server response is not good. instead of sending name as a string to you, it should return you "name" as an object like this:
"history": [
{
"id": "20",
"code": "mcw_5b97de588ce0c",
"date": "2018-09-11 17:25:12",
"status": "1",
"name":
{
"s":7,
"subject":"english",
"s":9,
"any_key":"rent bill"
},
"img": "shop.png"
}
I feel like server is returning you code string which you have written to process request from client. Please double check.
when receiving my json from my loop it comes as one big object
how do I prevent this can someone point me in the right direction or documents.
Log....
W/System.err: org.json.JSONException: Value {"1":{"id":1,"name":"Bitcoin","symbol":"BTC","website_slug":"bitcoin","rank":1,"circulating_supply":17153487,"total_supply":17153487,"max_supply":21000000,"quotes":{"USD":{"price":6720.93,"volume_24h":4367200000,"market_cap":115287385383,"percent_change_1h":-0.09,"percent_change_24h":2.07,"percent_change_7d":3.26}},"last_updated":1531828586},"1027":{"id":1027,"name":"Ethereum","symbol":"ETH","website_slug":"ethereum","rank":2,"circulating_supply":100744923,"total_supply":100744923,"max_supply":null,"quotes":{"USD":{"price":472.777,"volume_24h":1774520000,"market_cap":47629882298,"percent_change_1h":-0.45,"percent_change_24h":0.3,"percent_change_7d":5.32}},"last_updated":1531828591},"52":{"id":52,"name":"XRP","symbol":"XRP","website_slug":"ripple","rank":3,"circulating_supply":39262444717,"total_supply":99991916481,"max_supply":100000000000,"quotes":{"USD":{"price":0.473278,"volume_24h":269811000,"market_cap":18582051311,"percent_change_1h":-0.18,"percent_change_24h":2.43,"percent_change_7d":4.17}},"last_updated":1531828571},"1831":{"id":1831,"name":"Bitcoin Cash","symbol":"BCH","website_slug":"bitcoin-cash","rank":4,"circulating_supply":17242013,"total_supply":17242013,"max_supply":21000000,"quotes":{"USD":{"price":793.963,"volume_24h":471637000,"market_cap":13689519971,"percent_change_1h":-0.47,"percent_change_24h":3.58,"percent_change_7d":12.07}},"last_updated":1531828592},"1765":{"id":1765,"name":"EOS","symbol":"EOS","website_slug":"eos","rank":5,"circulating_supply":896149492,"total_supply":900000000,"max_supply":1000000000,"quotes":{"USD":{"price":7.94815,"volume_24h":666448000,"market_cap":7122730586,"percent_change_1h":-0.29,"percent_change_24h":2.5,"percent_change_7d":6.31}},"last_updated":1531828590},"2":{"id":2,"name":"Litecoin","symbol":"LTC","website_slug":"litecoin","rank":6,"circulating_supply":57444758,"total_supply":57444758,"max_supply":84000000,"quotes":{"USD":{"price":83.7447,"volume_24h":283495000,"market_cap":4810693998,"percent_change_1h":-0.17,"percent_change_24h":1.63,"percent_change_7d":8.91}},"last_updated":1531828567},"512":{"id":512,"name":"Stellar","symbol":"XLM","website_slug":"stellar","rank":7,"circulating_supply":18766530971,"total_supply":104125061584,"max_supply":null,"quotes":{"USD":{"price":0.231804,"volume_24h":49352700,"market_cap":4350156945,"percent_change_1h":-0.94,"percent_change_24h":0.8,"percent_change_7d":17.92}},"last_updated":1531828584},"2010":{"id":2010,"name":"Cardano","symbol":"ADA","website_slug":"cardano","rank":8,"circulating_supply":25927070538,"total_supply":31112483745,"max_supply":45000000000,"quotes":{"USD":{"price":0.152682,"volume_24h":86195700,"market_cap":3958596984,"percent_change_1h":0.16,"percent_change_24h":1.2,"percent_change_7d":15.48}},"last_updated":1531828594},"1720":{"id":1720,"name":"IOTA","symbol":"MIOTA","website_slug":"iota","rank":9,"circulating_supply":2779530283,"total_supply":2779530283,"max_supply":2779530283,"quotes":{"USD":{"price":1.06608,"volume_24h":45845200,"market_cap":2963201644,"percent_change_1h":-0.49,"percent_change_24h":0.44,"percent_change_7d":8.21}},"last_updated":1531828590},"825":{"id":825,"name":"Tether","symbol":"USDT","website_slug":"tether","rank":10,"circulating_supply":2707140346,"total_supply":3080109502,"max_supply":null,"quotes":{"USD":{"price":1.00215,"volume_24h":2728850000,"market_cap":2712960697,"percent_change_1h":0.11,"percent_change_24h":0.45,"percent_change_7d":-0.16}},"last_updated":1531828588},"1958":{"id":1958,"name":"TRON","symbol":"TRX","website_slug":"tron","rank":11,"circulating_supply":65748111645,"total_supply":99000000000,"max_supply":null,"quotes":{"USD":{"price":0.0367706,"volume_24h":191259000,"market_cap":2417597514,"percent_change_1h":0.03,"percent_change_24h":1.55,"percent_change_7d":8.49}},"last_updated":1531828593},"1376":{"id":1376,"name":"NEO","symbol":"NEO","website_slug":"neo","rank":12,"circulating_supply":65000000,"total_supply":100000000,"max_supply":100000000,"quotes":{"USD":{"price":36.2949,"volume_24h":128189
here is my code for the request
public ArrayList getCoin () {
firstlist.clear();
final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
Constants.URL_JSON, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray coinArray = response.getJSONArray("data");
for (int i = 0; i < coinArray.length(); i++) {
JSONObject coinOBJ = coinArray.getJSONObject(i);
CoinMarketAPI coin = new CoinMarketAPI();
// coin.setId(coinOBJ.getString("id"));
//coin.setName(coinOBJ.getString("name"));
//coin.setSymbol(coinOBJ.getString("symbol"));
//coin.setWebsite_slug(coinOBJ.getString("website_slug"));
// coin.setRank(coinOBJ.getString("rank"));
// coin.setCirculating_supply(coinOBJ.getString("circulating_supply"));
// coin.setTotal_supply(coinOBJ.getString("total_supply"));
// coin.setQuotes(coinOBJ.getString("quotes"));
// coin.setUSD(coinOBJ.getString("USD"));
// coin.setPrice(coinOBJ.getString("price"));
Log.d(TAG, coin.getName());
firstlist.add(coin);
}
JSON
{
"data": {
"1": {
"id": 1,
"name": "Bitcoin",
"symbol": "BTC",
"website_slug": "bitcoin",
"rank": 1,
"circulating_supply": 17008162.0,
"total_supply": 17008162.0,
"max_supply": 21000000.0,
"quotes": {
"USD": {
"price": 9024.09,
"volume_24h": 8765400000.0,
"market_cap": 153483184623.0,
"percent_change_1h": -2.31,
"percent_change_24h": -4.18,
"percent_change_7d": -0.47
}
},
"last_updated": 1525137271
},
"1027": {
"id": 1027,
"name": "Ethereum",
"symbol": "ETH",
"website_slug": "ethereum",
"rank": 2,
"circulating_supply": 99151888.0,
"total_supply": 99151888.0,
"max_supply": null,
"quotes": {
"USD": {
"price": 642.399,
"volume_24h": 2871290000.0,
"market_cap": 63695073558.0,
"percent_change_1h": -3.75,
"percent_change_24h": -7.01,
"percent_change_7d": -2.32
}
},
NOTE some lines are commented out to prevent further errors.
Im think the error is to do the jsonarray response line but not to sure how to fix it. any help will be greatly appreciated.
data is object, not an array, so you can loop by iterator like this
JSONObject coinArray = response.getJSONObject("data");
Iterator<String> iter = coinArray.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
Object coinOBJ = coinArray.get(key);
CoinMarketAPI coin = new CoinMarketAPI();
coin.setId(coinOBJ.getString("id"));
coin.setName(coinOBJ.getString("name"));
coin.setSymbol(coinOBJ.getString("symbol"));
coin.setWebsite_slug(coinOBJ.getString("website_slug"));
coin.setRank(Integer.parseInt(coinOBJ.getString("rank")));
coin.setCirculating_supply(coinOBJ.getString("circulating_supply"));
coin.setTotal_supply(coinOBJ.getString("total_supply"));
coin.setQuotes(coinOBJ.getString("quotes"));
coin.setUSD(coinOBJ.getString("USD"));
coin.setPrice(coinOBJ.getString("price"));
Log.d(TAG, coin.getName());
firstlist.add(coin);
} catch (JSONException e) {
// Something went wrong!
}
}
Let me explain it for you. What I did is that "data" was a JsonObject and has multiple objects Inside itself. so I converted data Into Json array by jsonObject.names(); Now I will get each object inside data through for loop.
JSONObject jsonObject = response.getJSONObject("data");
JSONArray jsonArray = jsonObject.names();
Log.e(tag,jsonArray.toString());
for(int i=0;i<jsonArray.length();i++){
JSONObject getObjectFromJsonArray=jsonObject.getJSONObject(jsonArray.getString(i));
CoinMarketAPI coin=new CoinMarketAPI();
coin.setId(getObjectFromJsonArray.getString("id"));
coin.setName(getObjectFromJsonArray.getString("name"));
coin.setSymbol(getObjectFromJsonArray.getString("symbol"));
coin.setWebsite_slug(getObjectFromJsonArray.getString("website_slug"));
coin.setRank(getObjectFromJsonArray.getString("rank"));
coin.setCirculating_supply(getObjectFromJsonArray.getString("circulating_supply"));
coin.setTotal_supply(getObjectFromJsonArray.getString("total_supply"));
JSONObject qoutes = getObjectFromJsonArray.getJSONObject("quotes");
JSONObject USD = qoutes.getJSONObject("USD");
coin.setPrice(USD.getString("price"));
firstlist.add(coin);
}
I have a response form server as :
[
{
"ID": "1",
"Title": "BIRATNAGAR",
"BankID": "1",
"BranchCode": "0",
"LocationID": "71500200",
"IsActive": "yes"
},
{
"ID": "2",
"Title": "BIRATNAGAR",
"BankID": "1",
"BranchCode": "0",
"LocationID": "71500900",
"IsActive": "yes"
},
{
"ID": "3",
"Title": "BIRATNAGAR",
"BankID": "1",
"BranchCode": "0",
"LocationID": "94361117",
"IsActive": "yes"
}
]
I have retrofit api as:
#POST("authapp/Restserver/api/Masterdata/getBranchListByBank")
Call> getBranchListByBank(#Query("api_key") String id);
I have called it as:
RetrofitArrayAPI service = retrofit.create(RetrofitArrayAPI.class);
Call<List<BankBranch>> call = service.getBranchListByBank(s);
call.enqueue(new Callback<List<BankBranch>>() {
#Override
public void onResponse(Call<List<BankBranch>> call, Response<List<BankBranch>> response) {
try {
List<BankBranch> banks = response.body();
for (int i = 0; i < banks.size(); i++) {
String id = banks.get(i).getTitle();
String name = banks.get(i).getID();
String marks = banks.get(i).getIsActive();
Log.i("ashihs", id + " " + marks + " " + name);
}
} catch (Exception e) {
Log.d("onResponse", "There is an error");
e.printStackTrace();
}
}
#Override
public void onFailure(Call<List<BankBranch>> call, Throwable t) {
Log.d("onFailure", t.toString());
}
});
But I cannot get the list of the bank branch. I get error as :
java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
Can any one help me?
Thanks in advance.
U probably got bad Api request it schould look like this:
api:
#POST("authapp/Restserver/api/Masterdata/getBranchListByBank")
Call<List<BankBranch>> getBranchListByBank(#Query("api_key") String id);
And the method schould look like this:
Call<List<BankBranch>> response = apiCall.getBranchListByBank(id);
response.enqueue(new Callback<List<BankBranch>>() {
#Override
public void onResponse(Call<List<BankBranch>> call, Response<List<BankBranch>> response) {
List<BankBranch> bankBranch = response.body();
}
#Override
public void onFailure(Call<List<BankBranch>> call, Throwable t) {
}
});
}
make sure Your model BankBranch fit the JSON response;
I am fairly new to Android development and I am creating an app that requires me to consume the Zomato Rest API. I am using the Koush ION library https://github.com/koush/ion for sending the http request and receiving a response. For using this library, I simply create a model java class with the keys as java instance variables and call this line of code.
Ion.with(getActivity())
.load("https://developers.zomato.com/api/v2.1/geocode?lat=25.12819&lon=55.22724")
.setHeader("user-key",my-user-key)
.asJsonArray()
.setCallback(new FutureCallback<JsonArray>() {
#Override
public void onCompleted(Exception e, JsonArray result) {
if (e != null) {
Log.d("FoodFragment", "Error loading food"+e.toString());
Toast.makeText(getActivity(), "error loading food", Toast.LENGTH_LONG).show();
return;
}
else{
Log.d("FoodFragment", "Size= " + result.size() + "; " + result.toString());
sTrips = (List<RestaurantsZomato>) new Gson().fromJson(result.toString(), new TypeToken<List<RestaurantsZomato>>() {
}.getType());
adapter = new RestaurantAdapter(sTrips);
recyclerView.setAdapter(adapter);
mSwipeRefreshLayout.setRefreshing(false);
((RestaurantAdapter) adapter).setOnItemClickListener(new RestaurantAdapter.MyClickListener() {
#Override
public void onItemClick(int position, View v) {
Toast.makeText(getActivity(), "Item Clicked", Toast.LENGTH_LONG).show();
}
});
}
}
});
}
As per the Zomato API documentation, the response will look something like this -
{"nearby_restaurants": {
"1": {
"restaurant": {
}
},
"2": {
"restaurant": {
}
},
"3": {
"restaurant": {
}
},
"4": {
"restaurant": {
}
},
"5": {
"restaurant": {
}
},
"6": {
"restaurant": {
}
},
"7": {
}
},
"8": {
"restaurant": {
}
},
"9": {
"restaurant": {
}
}
And my RestaurantZomato class looks like this -
public class RestaurantsZomato {
public NearbyRestaurants nearby_restaurants;
public static class NearbyRestaurants {
public List<RestaurantDetails> restaurant;
}}
And RestaurantDetails class has everything inside the "restaurant" tag. My question how to represent "1", "2", "3" etc that is present in the JsonResponse in my Model class.
I'm sorry if this question is stupid. As I said I'm new to Android development and any resources that point me in the right direction will be much appreciated!
In the Json format this
{
"nearby_restaurants":{
"1":{
"restaurant":{
}
},
"2":{
"restaurant":{
}
}
}
}
corresponds to an object "nearby_restaurants" that contains two objects "1" and "2" that both contains the object "restaurant" with empty value.
You are trying to fill a java List object, but in your Json doesn't exist any list or array!
Look at this and this and you will solve your problem. :-)
EDIT
try this code
JsonObject jsonObject = yourJsonElement.getAsJsonObject();
JsonObject nearby_restaurants = jsonObject.get("nearby_restaurants").getAsJsonObject();
Set<Entry<String, JsonElement>> objects = nearby_restaurants.entrySet();
Gson gson = new Gson();
for (Entry<String, JsonElement> entry : objects) {
System.out.println(entry.getKey() + "/" + entry.getValue());
}
public List< RestaurantDetails> restaurant; return Array
public RestaurantDetails restaurant; return Object
Your API return Object. Not return Array
Try this!!
public class RestaurantsZomato {
public NearbyRestaurants nearby_restaurants;
public static class NearbyRestaurants {
public RestaurantDetails restaurant;
}}
Update
Your Json String return JsonObject. You must use JsonObject
Ion.with(context)
.load("https://developers.zomato.com/api/v2.1/geocode?lat=25.12819&lon=55.22724")
.asJsonObject()
.setCallback(new FutureCallback<JsonObject>() {
#Override
public void onCompleted(Exception e, JsonObject result) {
// do stuff with the result or error
}
});
The problem is that you are receiving a JSON Object inside "nearby_restaurants" and trying to fetch it as a JSONArray. As you can see in the Zomato response there are no [] so there is no json array only objects.