I have been able to get a string from an url, using volley. This string is now shown as one block in a textview. But I would like to be able to display this data in individual textviews. How could I do this?
Maybe important to know: I'm completely new at programming and this is my first week I'm doing this. So my method I used could be strange, and this might be a stupid question, but I'm just trying to learn, and to get the result I want.
This is the code I have now, to get the data from the url:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text);
queue = Volley.newRequestQueue(this);
StringRequest request = new StringRequest(Request.Method.GET, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
textView.setText(response.toString());
Toast.makeText(MainActivity.this,response.toString(),Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("error",error.toString());
}
});
queue.add(request);
And this is how the result from the GET from the url looks like:
{"DeliveryDetailId":91003,"Delivery":{"DeliveryId":91,"DeliveryNumber":"1248","DropLocation":null,"DeliveryState":0},"ProductNumber":null,"Description":null,"PickLocation":"104","LocationCheck":null,"Quantity":64.0,"Histories":[],"BinNumberToUse":null}
So in this case I would like to have textviews which show the DeliveryID, Picklocation and Quantity. How can I extract this info from the string, so I can show it in the Textviews?
create model classes like below and store the response in Response.class
Then you can able to access DeliveryID by calling getDeliveryID()
-----------------------------------com.saranga.app.model.Delivery.java-----------------------------------
package com.saranga.app.model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Delivery {
#SerializedName("DeliveryId")
#Expose
private Integer deliveryId;
#SerializedName("DeliveryNumber")
#Expose
private String deliveryNumber;
#SerializedName("DropLocation")
#Expose
private Object dropLocation;
#SerializedName("DeliveryState")
#Expose
private Integer deliveryState;
public Integer getDeliveryId() {
return deliveryId;
}
public void setDeliveryId(Integer deliveryId) {
this.deliveryId = deliveryId;
}
public String getDeliveryNumber() {
return deliveryNumber;
}
public void setDeliveryNumber(String deliveryNumber) {
this.deliveryNumber = deliveryNumber;
}
public Object getDropLocation() {
return dropLocation;
}
public void setDropLocation(Object dropLocation) {
this.dropLocation = dropLocation;
}
public Integer getDeliveryState() {
return deliveryState;
}
public void setDeliveryState(Integer deliveryState) {
this.deliveryState = deliveryState;
}
}
-----------------------------------com.saranga.app.model.Response.java-----------------------------------
package com.saranga.app.model;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Response {
#SerializedName("DeliveryDetailId")
#Expose
private Integer deliveryDetailId;
#SerializedName("Delivery")
#Expose
private Delivery delivery;
#SerializedName("ProductNumber")
#Expose
private Object productNumber;
#SerializedName("Description")
#Expose
private Object description;
#SerializedName("PickLocation")
#Expose
private String pickLocation;
#SerializedName("LocationCheck")
#Expose
private Object locationCheck;
#SerializedName("Quantity")
#Expose
private Double quantity;
#SerializedName("Histories")
#Expose
private List<Object> histories = null;
#SerializedName("BinNumberToUse")
#Expose
private Object binNumberToUse;
public Integer getDeliveryDetailId() {
return deliveryDetailId;
}
public void setDeliveryDetailId(Integer deliveryDetailId) {
this.deliveryDetailId = deliveryDetailId;
}
public Delivery getDelivery() {
return delivery;
}
public void setDelivery(Delivery delivery) {
this.delivery = delivery;
}
public Object getProductNumber() {
return productNumber;
}
public void setProductNumber(Object productNumber) {
this.productNumber = productNumber;
}
public Object getDescription() {
return description;
}
public void setDescription(Object description) {
this.description = description;
}
public String getPickLocation() {
return pickLocation;
}
public void setPickLocation(String pickLocation) {
this.pickLocation = pickLocation;
}
public Object getLocationCheck() {
return locationCheck;
}
public void setLocationCheck(Object locationCheck) {
this.locationCheck = locationCheck;
}
public Double getQuantity() {
return quantity;
}
public void setQuantity(Double quantity) {
this.quantity = quantity;
}
public List<Object> getHistories() {
return histories;
}
public void setHistories(List<Object> histories) {
this.histories = histories;
}
public Object getBinNumberToUse() {
return binNumberToUse;
}
public void setBinNumberToUse(Object binNumberToUse) {
this.binNumberToUse = binNumberToUse;
}
}
You need to decode your JSONObject and individually get each element unless it's in a JSONArray in that case you need to loop through it
#Override
public void onResponse(String response) {
JSONObject json = new JSONObject(response);
textView.setText(json.getString("DeliveryDetailld"));
JSONObject details = json.getJSONObject("Delivery");
//Get data in Delivery Object
textView2.setText(details.getString("DeliveryId"));
}
I Am Having two JsonArray in Which there is JsonObject I have Got the String of each value but the problem is that when i am passing i into adapter I am getting indexOutofbound exeption because my value are getting Store in my object class so can any one help me how can i send my data to Object so that i can inflate to recyclerView.
private void callola() {
progressDialog = new ProgressDialog(CabBookingActivity.this);
progressDialog.setMessage("Loading ...");
progressDialog.setCancelable(false);
progressDialog.show();
final RequestQueue queue = Volley.newRequestQueue(CabBookingActivity.this);
String url = "https://www.reboundindia.com/app/application/ola/ride_estimate.php";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.setCancelable(true);
progressDialog.dismiss();
Log.e("sushil Call ola response", response);
try {
JSONObject mainObj = new JSONObject(response);
arrayList = new ArrayList<>();
String result = mainObj.getString("result");
int i, j;
ArrayList categoriess, Ride;
if (result.equals("606")) {
JSONObject message = mainObj.getJSONObject("message");
categories = message.getJSONArray("categories");
ride_estimate = message.getJSONArray("ride_estimate");
// JSONArray ride_estimate = message.getJSONArray("ride_estimate");
for (i = 0; i < categories.length(); i++) {
Log.e("sushil", String.valueOf(i));
jsonObject = categories.getJSONObject(i);
id = jsonObject.getString("id");
display_name = jsonObject.getString("display_name");
image = jsonObject.getString("image");
eta = jsonObject.getString("eta");
Log.e("OutPut", id + " " + eta + " " + image + " " + amount_min + " " + amount_max);
}
for (j = 0; j < ride_estimate.length(); j++) {
Log.e("sushil", String.valueOf(j));
rideestimate = ride_estimate.getJSONObject(j);
distance = rideestimate.getString("distance");
amount_min = rideestimate.getString("amount_min");
amount_max = rideestimate.getString("amount_max");
category = rideestimate.getString("category");
}
}
OlaUberModel olaUberModel = new OlaUberModel(category, display_name, amount_min, eta, image, amount_max);
arrayList.add(olaUberModel);
Log.e("sushil ride_estimate", distance + " " + amount_min + " " + amount_max);
AdapterOlaUber adapterOlaUber = new AdapterOlaUber(context, arrayList, CabBookingActivity.this);
recyclerView.setAdapter(adapterOlaUber);
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Log.e("error", error.toString());
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("pickup_lat", "" + pickLat);
params.put("pickup_lng", "" + pickLong);
params.put("drop_lat", String.valueOf(dropLat));
params.put("drop_lng", String.valueOf(dropLong));
params.put("category", "all");
params.put("token", token);
Log.e("sushil param", String.valueOf(params));
return params;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
90000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(stringRequest);
}
Here is my JSONRESPONSE
{
"result":"606",
"message":{
"categories":[
{
"id":"micro",
"display_name":"Micro",
"currency":"INR",
"distance_unit":"kilometre",
"time_unit":"minute",
"eta":5,
"distance":"0.7",
"ride_later_enabled":"true",
"image":"http:\/\/d1foexe15giopy.cloudfront.net\/micro.png",
"cancellation_policy":{
"cancellation_charge":50,
"currency":"INR",
"cancellation_charge_applies_after_time":5,
"time_unit":"minute"
},
"fare_breakup":[
{
"type":"flat_rate",
"minimum_distance":0,
"minimum_time":0,
"base_fare":50,
"minimum_fare":60,
"cost_per_distance":6,
"waiting_cost_per_minute":0,
"ride_cost_per_minute":1.5,
"surcharge":[
],
"rates_lower_than_usual":false,
"rates_higher_than_usual":false
}
]
},
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ }
],
"ride_estimate":[
{
"category":"prime_play",
"distance":3.99,
"travel_time_in_minutes":30,
"amount_min":155,
"amount_max":163,
"discounts":{
"discount_type":null,
"discount_code":null,
"discount_mode":null,
"discount":0,
"cashback":0
}
},
{ },
{ },
{ },
{ },
{ },
{ },
{ }
]
}
}
My Problem is that how can send the data in model.
My Model Should contain data Like id,displayName,amountMin,eta,image,amountMax
First of all you need to make two different models for category and ride_estimate.Because they both are in different loops. Also try this
for (j = 0; j < ride_estimate.length(); j++) {
Log.e("sushil", String.valueOf(j));
rideestimate = ride_estimate.getJSONObject(j);
distance = rideestimate.getString("distance");
amount_min = rideestimate.getString("amount_min");
amount_max = rideestimate.getString("amount_max");
category = rideestimate.getString("category");
OlaUberModel olaUberModel = new OlaUberModel(category, display_name, amount_min, eta, image, amount_max);
arrayList.add(olaUberModel);
}
May be this would helpful for you..
Thanks!
replace
eta = jsonObject.getString("eta");
by
int eta = jsonObject.getInt("eta");
On the basis of id of any cab type "prime" you can fetch image. what say
create some class as per your data
-----------------------------------com.example.CancellationPolicy.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class CancellationPolicy {
#SerializedName("cancellation_charge")
#Expose
private Integer cancellationCharge;
#SerializedName("currency")
#Expose
private String currency;
#SerializedName("cancellation_charge_applies_after_time")
#Expose
private Integer cancellationChargeAppliesAfterTime;
#SerializedName("time_unit")
#Expose
private String timeUnit;
public Integer getCancellationCharge() {
return cancellationCharge;
}
public void setCancellationCharge(Integer cancellationCharge) {
this.cancellationCharge = cancellationCharge;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public Integer getCancellationChargeAppliesAfterTime() {
return cancellationChargeAppliesAfterTime;
}
public void setCancellationChargeAppliesAfterTime(Integer cancellationChargeAppliesAfterTime) {
this.cancellationChargeAppliesAfterTime = cancellationChargeAppliesAfterTime;
}
public String getTimeUnit() {
return timeUnit;
}
public void setTimeUnit(String timeUnit) {
this.timeUnit = timeUnit;
}
}
-----------------------------------com.example.Category.java-----------------------------------
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Category {
#SerializedName("id")
#Expose
private String id;
#SerializedName("display_name")
#Expose
private String displayName;
#SerializedName("currency")
#Expose
private String currency;
#SerializedName("distance_unit")
#Expose
private String distanceUnit;
#SerializedName("time_unit")
#Expose
private String timeUnit;
#SerializedName("eta")
#Expose
private Integer eta;
#SerializedName("distance")
#Expose
private String distance;
#SerializedName("ride_later_enabled")
#Expose
private String rideLaterEnabled;
#SerializedName("image")
#Expose
private String image;
#SerializedName("cancellation_policy")
#Expose
private CancellationPolicy cancellationPolicy;
#SerializedName("fare_breakup")
#Expose
private List<FareBreakup> fareBreakup = null;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public String getDistanceUnit() {
return distanceUnit;
}
public void setDistanceUnit(String distanceUnit) {
this.distanceUnit = distanceUnit;
}
public String getTimeUnit() {
return timeUnit;
}
public void setTimeUnit(String timeUnit) {
this.timeUnit = timeUnit;
}
public Integer getEta() {
return eta;
}
public void setEta(Integer eta) {
this.eta = eta;
}
public String getDistance() {
return distance;
}
public void setDistance(String distance) {
this.distance = distance;
}
public String getRideLaterEnabled() {
return rideLaterEnabled;
}
public void setRideLaterEnabled(String rideLaterEnabled) {
this.rideLaterEnabled = rideLaterEnabled;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public CancellationPolicy getCancellationPolicy() {
return cancellationPolicy;
}
public void setCancellationPolicy(CancellationPolicy cancellationPolicy) {
this.cancellationPolicy = cancellationPolicy;
}
public List<FareBreakup> getFareBreakup() {
return fareBreakup;
}
public void setFareBreakup(List<FareBreakup> fareBreakup) {
this.fareBreakup = fareBreakup;
}
}
-----------------------------------com.example.Discounts.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Discounts {
#SerializedName("discount_type")
#Expose
private Object discountType;
#SerializedName("discount_code")
#Expose
private Object discountCode;
#SerializedName("discount_mode")
#Expose
private Object discountMode;
#SerializedName("discount")
#Expose
private Integer discount;
#SerializedName("cashback")
#Expose
private Integer cashback;
public Object getDiscountType() {
return discountType;
}
public void setDiscountType(Object discountType) {
this.discountType = discountType;
}
public Object getDiscountCode() {
return discountCode;
}
public void setDiscountCode(Object discountCode) {
this.discountCode = discountCode;
}
public Object getDiscountMode() {
return discountMode;
}
public void setDiscountMode(Object discountMode) {
this.discountMode = discountMode;
}
public Integer getDiscount() {
return discount;
}
public void setDiscount(Integer discount) {
this.discount = discount;
}
public Integer getCashback() {
return cashback;
}
public void setCashback(Integer cashback) {
this.cashback = cashback;
}
}
-----------------------------------com.example.Example.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("result")
#Expose
private String result;
#SerializedName("message")
#Expose
private Message message;
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public Message getMessage() {
return message;
}
public void setMessage(Message message) {
this.message = message;
}
}
-----------------------------------com.example.FareBreakup.java-----------------------------------
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class FareBreakup {
#SerializedName("type")
#Expose
private String type;
#SerializedName("minimum_distance")
#Expose
private Integer minimumDistance;
#SerializedName("minimum_time")
#Expose
private Integer minimumTime;
#SerializedName("base_fare")
#Expose
private Integer baseFare;
#SerializedName("minimum_fare")
#Expose
private Integer minimumFare;
#SerializedName("cost_per_distance")
#Expose
private Integer costPerDistance;
#SerializedName("waiting_cost_per_minute")
#Expose
private Integer waitingCostPerMinute;
#SerializedName("ride_cost_per_minute")
#Expose
private Double rideCostPerMinute;
#SerializedName("surcharge")
#Expose
private List<Object> surcharge = null;
#SerializedName("rates_lower_than_usual")
#Expose
private Boolean ratesLowerThanUsual;
#SerializedName("rates_higher_than_usual")
#Expose
private Boolean ratesHigherThanUsual;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Integer getMinimumDistance() {
return minimumDistance;
}
public void setMinimumDistance(Integer minimumDistance) {
this.minimumDistance = minimumDistance;
}
public Integer getMinimumTime() {
return minimumTime;
}
public void setMinimumTime(Integer minimumTime) {
this.minimumTime = minimumTime;
}
public Integer getBaseFare() {
return baseFare;
}
public void setBaseFare(Integer baseFare) {
this.baseFare = baseFare;
}
public Integer getMinimumFare() {
return minimumFare;
}
public void setMinimumFare(Integer minimumFare) {
this.minimumFare = minimumFare;
}
public Integer getCostPerDistance() {
return costPerDistance;
}
public void setCostPerDistance(Integer costPerDistance) {
this.costPerDistance = costPerDistance;
}
public Integer getWaitingCostPerMinute() {
return waitingCostPerMinute;
}
public void setWaitingCostPerMinute(Integer waitingCostPerMinute) {
this.waitingCostPerMinute = waitingCostPerMinute;
}
public Double getRideCostPerMinute() {
return rideCostPerMinute;
}
public void setRideCostPerMinute(Double rideCostPerMinute) {
this.rideCostPerMinute = rideCostPerMinute;
}
public List<Object> getSurcharge() {
return surcharge;
}
public void setSurcharge(List<Object> surcharge) {
this.surcharge = surcharge;
}
public Boolean getRatesLowerThanUsual() {
return ratesLowerThanUsual;
}
public void setRatesLowerThanUsual(Boolean ratesLowerThanUsual) {
this.ratesLowerThanUsual = ratesLowerThanUsual;
}
public Boolean getRatesHigherThanUsual() {
return ratesHigherThanUsual;
}
public void setRatesHigherThanUsual(Boolean ratesHigherThanUsual) {
this.ratesHigherThanUsual = ratesHigherThanUsual;
}
}
-----------------------------------com.example.Message.java-----------------------------------
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Message {
#SerializedName("categories")
#Expose
private List<Category> categories = null;
#SerializedName("ride_estimate")
#Expose
private List<RideEstimate> rideEstimate = null;
public List<Category> getCategories() {
return categories;
}
public void setCategories(List<Category> categories) {
this.categories = categories;
}
public List<RideEstimate> getRideEstimate() {
return rideEstimate;
}
public void setRideEstimate(List<RideEstimate> rideEstimate) {
this.rideEstimate = rideEstimate;
}
}
-----------------------------------com.example.RideEstimate.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class RideEstimate {
#SerializedName("category")
#Expose
private String category;
#SerializedName("distance")
#Expose
private Double distance;
#SerializedName("travel_time_in_minutes")
#Expose
private Integer travelTimeInMinutes;
#SerializedName("amount_min")
#Expose
private Integer amountMin;
#SerializedName("amount_max")
#Expose
private Integer amountMax;
#SerializedName("discounts")
#Expose
private Discounts discounts;
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public Double getDistance() {
return distance;
}
public void setDistance(Double distance) {
this.distance = distance;
}
public Integer getTravelTimeInMinutes() {
return travelTimeInMinutes;
}
public void setTravelTimeInMinutes(Integer travelTimeInMinutes) {
this.travelTimeInMinutes = travelTimeInMinutes;
}
public Integer getAmountMin() {
return amountMin;
}
public void setAmountMin(Integer amountMin) {
this.amountMin = amountMin;
}
public Integer getAmountMax() {
return amountMax;
}
public void setAmountMax(Integer amountMax) {
this.amountMax = amountMax;
}
public Discounts getDiscounts() {
return discounts;
}
public void setDiscounts(Discounts discounts) {
this.discounts = discounts;
}
}
Now compile a library compile 'com.google.code.gson:gson:2.8.2'
then write few line to get your data fill in class
Gson gson = new Gson();
Example example = gson.fromJson(mainObj, Example.class);
Now you can try to fetch your categories like this
example.getCategories();
I have following code for retrieving web search results through google custom api
package google.custom.api.results.google.custom.api;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import com.google.gson.Gson;
public class handler {
public static boolean searchAndSaveGoogleCustomSearch() throws UnsupportedEncodingException
{
String apiKey="AIzaSyB21aUCd8HYMsHgo7APH-98ah-8tLgkPFM";
String cxId="005621018181405156379:yvdukowvdte";
String keyToSearch="News";
String urlToSearch="https://www.googleapis.com/customsearch/v1?key=" +apiKey+ "&cx="+cxId
+"&alt=json"+"&q="+keyToSearch;
try {
URL url=new URL(urlToSearch);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
BufferedReader br = new BufferedReader(new InputStreamReader ( ( conn.getInputStream() ) ) );
GoogleCustomApiResult result = new Gson().fromJson(br, GoogleCustomApiResult.class);
System.out.println(result);
conn.disconnect();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
public static void main(String[] args) throws UnsupportedEncodingException {
searchAndSaveGoogleCustomSearch();
System.out.println("Google Crawl done.");
}
}
And here's how i have been trying to retrieve the java object from json results
package google.custom.api.results.google.custom.api;
import java.util.List;
public class GoogleCustomApiResult
{
private String link;
private String htmlFormattedUrl;
private List<GoogleCustomApiResult> items;
public String getLink() {
return link;
}
public String getUrl() {
return htmlFormattedUrl;
}
public void setUrl(String htmlFormattedUrl) {
this.htmlFormattedUrl = htmlFormattedUrl;
}
public List<GoogleCustomApiResult> getItems() {
return items;
}
public void setLink(String link) {
this.link = link;
}
public void setGroups(List<GoogleCustomApiResult> items) {
this.items = items;
}
public void getThing (int i) {
System.out.println(items.get(i));
}
public String getLink(int i) {
return items.get(i).toString();
}
public String toString() {
return String.format("%s", link);
}
}
And also using this class
package com.til.et.mynewsletter.core.parser.json.google;
import java.util.List;
public class CustomApiResult
{
private String kind;
private String title;
private String htmlTitle;
private String link;
private String displayLink;
private String snippet;
private String htmlSnippet;
private String cacheId;
private String formattedUrl;
private String htmlFormattedUrl;
//private String htmlSnippet;
public String getKind() {
return kind;
}
public void setKind(String kind) {
this.kind = kind;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getHtmlTitle() {
return htmlTitle;
}
public void setHtmlTitle(String htmlTitle) {
this.htmlTitle = htmlTitle;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getDisplayLink() {
return displayLink;
}
public void setDisplayLink(String displayLink) {
this.displayLink = displayLink;
}
public String getSnippet() {
return snippet;
}
public void setSnippet(String snippet) {
this.snippet = snippet;
}
public String getHtmlSnippet() {
return htmlSnippet;
}
public void setHtmlSnippet(String htmlSnippet) {
this.htmlSnippet = htmlSnippet;
}
public String getCacheId() {
return cacheId;
}
public void setCacheId(String cacheId) {
this.cacheId = cacheId;
}
public String getFormattedUrl() {
return formattedUrl;
}
public void setFormattedUrl(String formattedUrl) {
this.formattedUrl = formattedUrl;
}
public String getHtmlFormattedUrl() {
return htmlFormattedUrl;
}
public void setHtmlFormattedUrl(String htmlFormattedUrl) {
this.htmlFormattedUrl = htmlFormattedUrl;
}
#Override
public String toString() {
return "GoogleCustomApiResult [title=" + title + ", link=" + link + ", snippet=" + snippet + ", cacheId="
+ cacheId + ", formattedUrl=" + formattedUrl + ", htmlFormattedUrl=" + htmlFormattedUrl + "]";
}
But the java object returned is null every time. I am new to Json and do not know how to parse the result to get the java object populated with values.
The Url is returning the result but the values are not going into java object. please help me out.
Looking at your response you're not mapping exactly the same json structure with you model GoogleCustomApiResult cause a lot of fields are missing.
You have two options:
Map the exactly json structure (Don't try to do this cause you have a giant json!)
Parse your response to get the list of objects you want (recommended).
Take a look at JsonParser in Gson API.
Also correct the error in your model class pointed by #Maraboc.
I am using XStream Library.
Link of xml service
http://webservices.nextbus.com/service/publicXMLFeed?command=routeConfig&a=ttc&r=54
My Classes......
package com.example.myjakcontest;
import java.util.List;
import com.thoughtworks.xstream.annotations.XStreamAlias;
public class Body {
#XStreamAlias("copyright")
private String _copyright;
private Route route;
public String get_copyright() {
return this._copyright;
}
public void set_copyright(String _copyright) {
this._copyright = _copyright;
}
public Route getRoute() {
return this.route;
}
public void setRoute(Route route) {
this.route = route;
}
}
package com.example.my**jakcontest;**
import java.util.List;
public class Direction{
private String _branch;
private String _name;
private String _tag;
private String _title;
private String _useForUI;
private List<Stop> stop;
public String get_branch(){
return this._branch;
}
public void set_branch(String _branch){
this._branch = _branch;
}
public String get_name(){
return this._name;
}
public void set_name(String _name){
this._name = _name;
}
public String get_tag(){
return this._tag;
}
public void set_tag(String _tag){
this._tag = _tag;
}
public String get_title(){
return this._title;
}
public void set_title(String _title){
this._title = _title;
}
public String get_useForUI(){
return this._useForUI;
}
public void set_useForUI(String _useForUI){
this._useForUI = _useForUI;
}
public List<Stop> getStop(){
return this.stop;
}
public void setStop(List<Stop> stop){
this.stop = stop;
}
}
Async Task
XStream x = new XStream();
x.alias("body", Body.class);
x.alias("stop", Stop.class);
x.alias("route", Route.class);
x.alias("direction", Direction.class);
x.alias("path", Path.class);
x.alias("point", Point.class);
x.addImplicitCollection(Route.class, "stop");
x.addImplicitCollection(Route.class, "direction");
x.addImplicitCollection(Route.class, "path");
x.addImplicitCollection(Direction.class, "stop");
x.addImplicitCollection(Path.class, "point");
Body object = (Body) x.fromXML(httpResponse.getEntity()
.getContent());
// Function converts XML to String
String xml = convertStreamToString(httpResponse.getEntity()
.getContent());
Body b = (Body) x.fromXML(xml);
I have all the classes but in object "b" i am getting null.
Try JAXB .It s a standard way of doing it...!
refer the link www.javatpoint.com/jaxb-unmarshalling-example
I'm trying to parse a JSON string like this one
[
{
"updated_at":"2012-03-02 21:06:01",
"fetched_at":"2012-03-02 21:28:37.728840",
"description":null,
"language":null,
"title":"JOHN",
"url":"http://rus.JOHN.JOHN/rss.php",
"icon_url":null,
"logo_url":null,
"id":"4f4791da203d0c2d76000035",
"modified":"2012-03-02 23:28:58.840076"
},
{
"updated_at":"2012-03-02 14:07:44",
"fetched_at":"2012-03-02 21:28:37.033108",
"description":null,
"language":null,
"title":"PETER",
"url":"http://PETER.PETER.lv/rss.php",
"icon_url":null,
"logo_url":null,
"id":"4f476f61203d0c2d89000253",
"modified":"2012-03-02 23:28:57.928001"
}
]
into a list of objects.
List<ChannelSearchEnum> lcs = (List<ChannelSearchEnum>) new Gson().fromJson( jstring , ChannelSearchEnum.class);
Here's an object class I'm using.
import com.google.gson.annotations.SerializedName;
public class ChannelSearchEnum {
#SerializedName("updated_at")
private String updated_at;
#SerializedName("fetched_at")
private String fetched_at;
#SerializedName("description")
private String description;
#SerializedName("language")
private String language;
#SerializedName("title")
private String title;
#SerializedName("url")
private String url;
#SerializedName("icon_url")
private String icon_url;
#SerializedName("logo_url")
private String logo_url;
#SerializedName("id")
private String id;
#SerializedName("modified")
private String modified;
public final String get_Updated_at() {
return this.updated_at;
}
public final String get_Fetched_at() {
return this.fetched_at;
}
public final String get_Description() {
return this.description;
}
public final String get_Language() {
return this.language;
}
public final String get_Title() {
return this.title;
}
public final String get_Url() {
return this.url;
}
public final String get_Icon_url() {
return this.icon_url;
}
public final String get_Logo_url() {
return this.logo_url;
}
public final String get_Id() {
return this.id;
}
public final String get_Modified() {
return this.modified;
}
}
But it throws me with
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2
Any ideas how should I fix it?
The problem is you're telling Gson you have an object of your type. You don't. You have an array of objects of your type. You can't just try and cast the result like that and expect it to magically work ;)
The User guide for Gson Explains how to deal with this:
https://github.com/google/gson/blob/master/UserGuide.md
This will work:
ChannelSearchEnum[] enums = gson.fromJson(yourJson, ChannelSearchEnum[].class);
But this is better:
Type collectionType = new TypeToken<Collection<ChannelSearchEnum>>(){}.getType();
Collection<ChannelSearchEnum> enums = gson.fromJson(yourJson, collectionType);
The problem is that you are asking for an object of type ChannelSearchEnum but what you actually have is an object of type List<ChannelSearchEnum>.
You can achieve this with:
Type collectionType = new TypeToken<List<ChannelSearchEnum>>(){}.getType();
List<ChannelSearchEnum> lcs = (List<ChannelSearchEnum>) new Gson()
.fromJson( jstring , collectionType);
In my case JSON string:
[{"category":"College Affordability",
"uid":"150151",
"body":"Ended more than $60 billion in wasteful subsidies for big banks and used the savings to put the cost of college within reach for more families.",
"url":"http:\/\/www.whitehouse.gov\/economy\/middle-class\/helping middle-class-families-pay-for-college",
"url_title":"ending subsidies for student loan lenders",
"type":"Progress",
"path":"node\/150385"}]
and I print "category" and "url_title" in recycleview
Datum.class
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Datum {
#SerializedName("category")
#Expose
private String category;
#SerializedName("uid")
#Expose
private String uid;
#SerializedName("url_title")
#Expose
private String urlTitle;
/**
* #return The category
*/
public String getCategory() {
return category;
}
/**
* #param category The category
*/
public void setCategory(String category) {
this.category = category;
}
/**
* #return The uid
*/
public String getUid() {
return uid;
}
/**
* #param uid The uid
*/
public void setUid(String uid) {
this.uid = uid;
}
/**
* #return The urlTitle
*/
public String getUrlTitle() {
return urlTitle;
}
/**
* #param urlTitle The url_title
*/
public void setUrlTitle(String urlTitle) {
this.urlTitle = urlTitle;
}
}
RequestInterface
import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;
/**
* Created by Shweta.Chauhan on 13/07/16.
*/
public interface RequestInterface {
#GET("facts/json/progress/all")
Call<List<Datum>> getJSON();
}
DataAdapter
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Shweta.Chauhan on 13/07/16.
*/
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.MyViewHolder>{
private Context context;
private List<Datum> dataList;
public DataAdapter(Context context, List<Datum> dataList) {
this.context = context;
this.dataList = dataList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.data,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.categoryTV.setText(dataList.get(position).getCategory());
holder.urltitleTV.setText(dataList.get(position).getUrlTitle());
}
#Override
public int getItemCount() {
return dataList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder{
public TextView categoryTV, urltitleTV;
public MyViewHolder(View itemView) {
super(itemView);
categoryTV = (TextView) itemView.findViewById(R.id.txt_category);
urltitleTV = (TextView) itemView.findViewById(R.id.txt_urltitle);
}
}
}
and finally MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private DataAdapter dataAdapter;
private List<Datum> dataArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
}
private void initViews(){
recyclerView=(RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
loadJSON();
}
private void loadJSON(){
dataArrayList = new ArrayList<>();
Retrofit retrofit=new Retrofit.Builder().baseUrl("https://www.whitehouse.gov/").addConverterFactory(GsonConverterFactory.create()).build();
RequestInterface requestInterface=retrofit.create(RequestInterface.class);
Call<List<Datum>> call= requestInterface.getJSON();
call.enqueue(new Callback<List<Datum>>() {
#Override
public void onResponse(Call<List<Datum>> call, Response<List<Datum>> response) {
dataArrayList = response.body();
dataAdapter=new DataAdapter(getApplicationContext(),dataArrayList);
recyclerView.setAdapter(dataAdapter);
}
#Override
public void onFailure(Call<List<Datum>> call, Throwable t) {
Log.e("Error",t.getMessage());
}
});
}
}
Alternative could be
to make your response look like
myCustom_JSONResponse
{"master":[
{
"updated_at":"2012-03-02 21:06:01",
"fetched_at":"2012-03-02 21:28:37.728840",
"description":null,
"language":null,
"title":"JOHN",
"url":"http://rus.JOHN.JOHN/rss.php",
"icon_url":null,
"logo_url":null,
"id":"4f4791da203d0c2d76000035",
"modified":"2012-03-02 23:28:58.840076"
},
{
"updated_at":"2012-03-02 14:07:44",
"fetched_at":"2012-03-02 21:28:37.033108",
"description":null,
"language":null,
"title":"PETER",
"url":"http://PETER.PETER.lv/rss.php",
"icon_url":null,
"logo_url":null,
"id":"4f476f61203d0c2d89000253",
"modified":"2012-03-02 23:28:57.928001"
}
]
}
instead of
server_JSONResponse
[
{
"updated_at":"2012-03-02 21:06:01",
"fetched_at":"2012-03-02 21:28:37.728840",
"description":null,
"language":null,
"title":"JOHN",
"url":"http://rus.JOHN.JOHN/rss.php",
"icon_url":null,
"logo_url":null,
"id":"4f4791da203d0c2d76000035",
"modified":"2012-03-02 23:28:58.840076"
},
{
"updated_at":"2012-03-02 14:07:44",
"fetched_at":"2012-03-02 21:28:37.033108",
"description":null,
"language":null,
"title":"PETER",
"url":"http://PETER.PETER.lv/rss.php",
"icon_url":null,
"logo_url":null,
"id":"4f476f61203d0c2d89000253",
"modified":"2012-03-02 23:28:57.928001"
}
]
CODE
String server_JSONResponse =.... // the string in which you are getting your JSON Response after hitting URL
String myCustom_JSONResponse="";// in which we will keep our response after adding object element to it
MyClass apiResponse = new MyClass();
myCustom_JSONResponse="{\"master\":"+server_JSONResponse+"}";
apiResponse = gson.fromJson(myCustom_JSONResponse, MyClass .class);
After this it will be just any other GSON Parsing
This looks like a Json array list.Therefore its best to use ArrayList to handle the data. In your api end point add array list like this
#GET("places/")
Call<ArrayList<Place>> getNearbyPlaces(#Query("latitude") String latitude, #Query("longitude") String longitude);
according to GSON User guide, you cannot.
Collections Limitations
Can serialize collection of arbitrary objects but can not deserialize from it. Because there is no way for the user to indicate the type of the resulting object
Kotlin:
var list=ArrayList<Your class name>()
val listresult: Array<YOUR CLASS NAME> = Gson().fromJson(
YOUR JSON RESPONSE IN STRING,
Array<Your class name>:: class.java)
list.addAll(listresult)
You need to let Gson know additional type of your response as below
import com.google.common.reflect.TypeToken;
import java.lang.reflect.Type;
Type collectionType = new TypeToken<List<UserSite>>(){}.getType();
List<UserSite> userSites = gson.fromJson( response.getBody() , collectionType);
I am not sure if this is the best way to use GSON, but works for me. You can use some like this on the MainActivity:
public void readJson() {
dataArrayList = new ArrayList<>();
String json = "[\n" + IOHelper.getData(this) + "\n]\n";
Log.d(TAG, json);
try{
JSONArray channelSearchEnums = new JSONArray(json);
for(int i=0; i< channelSearchEnums.length(); i++)
{
JSONObject enum = channelSearchEnums.getJSONObject(i);
ChannelSearchEnum channel = new ChannelSearchEnum(
enum.getString("updated_at"), enum.getString("fetched_at"),
enum.getString("description"), enum.getString("language"),
enum.getString("title"), enum.getString("url"),
enum.getString("icon_url"), enum.getString("logo_url"),
enum.getString("id"), enum.getString("modified"))
dataArrayList.add(channel);
}
//The code and place you want to show your data
}catch (Exception e)
{
Log.d(TAG, e.getLocalizedMessage());
}
}
You only have strings, but if you would have doubles or int, you could put getDouble or getInt too.
The method of IOHelper class is the next (Here, the path is save on the internal Storage):
public static String getData(Context context) {
try {
File f = new File(context.getFilesDir().getPath() + "/" + fileName);
//check whether file exists
FileInputStream is = new FileInputStream(f);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
return new String(buffer);
} catch (IOException e) {
Log.e("TAG", "Error in Reading: " + e.getLocalizedMessage());
return null;
}
}
If you want more information about this, you can see this video, where I get the code of readJson(); and this thread where I get the code of getData().
public ChannelSearchEnum[] getChannelSearchEnum(Response response) {
return response.as(ChannelSearchEnum[].class, ObjectMapperType.GSON);
}
Above will solve and passing response will returned mapped object array of the class
Solution
I am using volley library. I parse response automatic in volley using GSON
[
{
"name": "Naruto: Shippuuden",
"description": "It has been two and a half years since Naruto Uzumaki left Konohagakure, the Hidden Leaf Village, for intense training following events which fueled his desire to be stronger. Now Akatsuki, the mysterious organization of elite rogue ninja, is closing in on their grand plan which may threaten the safety of the entire shinobi world.",
"Rating": "8.16",
"episode": 500,
"categorie":"Animation | Drama | Adventure",
"studio":"Studio Pierrot",
"img": "https://myanimelist.cdn-dena.com/images/anime/5/17407.jpg"
},
{
"name": "One Piece",
"description": "Gol D. Roger was known as the 'Pirate King',the strongest and most infamous being to have sailed the Grand Line. The capture and death of Roger by the World Government brought a change throughout the world. His last words before his death revealed the existence of the greatest treasure in the world, One Piece. It was this revelation that brought about the Grand Age of Pirates, men who dreamed of finding One Piece—which promises an unlimited amount of riches and fame—and quite possibly the pinnacle of glory and the title of the Pirate King.",
"Rating": "8.54",
"episode": 700,
"categorie":"Animation | Drama | Adventure",
"studio":"Toei Animation",
"img": "https://myanimelist.cdn-dena.com/images/anime/6/73245.jpg"
}
]
2.This my model
public class DataResponse implements Serializable {
#SerializedName("studio")
private String studio;
#SerializedName("img")
private String img;
#SerializedName("categorie")
private String categorie;
#SerializedName("Rating")
private String rating;
#SerializedName("name")
private String name;
#SerializedName("description")
private String description;
#SerializedName("episode")
private int episode;
public void setStudio(String studio){
this.studio = studio;
}
public String getStudio(){
return studio;
}
public void setImg(String img){
this.img = img;
}
public String getImg(){
return img;
}
public void setCategorie(String categorie){
this.categorie = categorie;
}
public String getCategorie(){
return categorie;
}
public void setRating(String rating){
this.rating = rating;
}
public String getRating(){
return rating;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setDescription(String description){
this.description = description;
}
public String getDescription(){
return description;
}
public void setEpisode(int episode){
this.episode = episode;
}
public int getEpisode(){
return episode;
}
#Override
public String toString(){
return
"Response{" +
"studio = '" + studio + '\'' +
",img = '" + img + '\'' +
",categorie = '" + categorie + '\'' +
",rating = '" + rating + '\'' +
",name = '" + name + '\'' +
",description = '" + description + '\'' +
",episode = '" + episode + '\'' +
"}";
}
}
my api method
define globle
private List<DataResponse> dataResponses = new ArrayList<>();
private void volleyAutomation(String url) {
JSONArray array = new JSONArray();
JsonArrayRequest request_json = new JsonArrayRequest(Request.Method.GET, url, array,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
dataResponses = Arrays.asList(gson.fromJson(response.toString(), DataResponse[].class));
rvList(dataResponses);
Log.d("respknce___", String.valueOf(dataResponses.size()));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(request_json);
}