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();
Related
I want to send array of objects like this to Spring REST Controller:
{
"measureList": [
{
"apiKey": "exampleKEY",
"stationId": "abcdef123",
"date": "2022-02-18T17:43:51.787535Z",
"temp": "20.5",
"humidity": "60.4",
"pressure": "1020.5",
"pm25": "100.0",
"pm25Corr": "150.0",
"pm10": "90.0"
},
{
"apiKey": "exampleKEY",
"stationId": "abcdef123",
"date": "2022-02-18T17:43:53.254309Z",
"temp": "20.5",
"humidity": "60.4",
"pressure": "1020.5",
"pm25": "100.0",
"pm25Corr": "150.0",
"pm10": "90.0"
}
]
}
I have created NewMeausurePackageDto like this:
package com.weather.server.domain.dto;
import java.util.ArrayList;
import java.util.List;
public class NewMeasurePackageDto {
private ArrayList<NewMeasureDto> measureList;
public NewMeasurePackageDto(ArrayList<NewMeasureDto> measureList) {
this.measureList = measureList;
}
public NewMeasurePackageDto() {
}
public ArrayList<NewMeasureDto> getNewMeasureListDto() {
return measureList;
}
#Override
public String toString() {
return "NewMeasurePackageDto{" +
"measureList=" + measureList +
'}';
}
}
NewMeasureDto class:
package com.weather.server.domain.dto;
public class NewMeasureDto {
private String apiKey;
private String stationId;
private String date;
private String temp;
private String humidity;
private String pressure;
private String pm25;
private String pm10;
private String pm25Corr;
//station_id
public NewMeasureDto() {
}
private NewMeasureDto(Builder builder){
apiKey = builder.apiKey;
stationId = builder.stationId;
date = builder.date;
temp = builder.temp;
humidity = builder.humidity;
pressure = builder.pressure;
pm25 = builder.pm25;
pm10 = builder.pm10;
pm25Corr = builder.pm25Corr;
}
public String getApiKey() {
return apiKey;
}
public String getStationID() {
return stationId;
}
public String getDate() {
return date;
}
public String getTemp() {
return temp;
}
public String getHumidity() {
return humidity;
}
public String getPressure() {
return pressure;
}
public String getPm25() {
return pm25;
}
public String getPm10() {
return pm10;
}
public String getPm25Corr() {
return pm25Corr;
}
public static final class Builder {
private String apiKey;
private String stationId;
private String date;
private String temp;
private String humidity;
private String pressure;
private String pm25;
private String pm10;
private String pm25Corr;
public Builder() {
}
public Builder apiKey(String apiKey) {
this.apiKey = apiKey;
return this;
}
public Builder stationID(String stationId) {
this.stationId = stationId;
return this;
}
public Builder date(String date) {
this.date = date;
return this;
}
public Builder temp(String temp) {
this.temp = temp;
return this;
}
public Builder humidity(String humidity) {
this.humidity = humidity;
return this;
}
public Builder pressure(String pressure){
this.pressure = pressure;
return this;
}
public Builder pm25(String pm25){
this.pm25 = pm25;
return this;
}
public Builder pm10(String pm10){
this.pm10 = pm10;
return this;
}
public Builder pm25Corr(String pm25Corr){
this.pm25Corr = pm25Corr;
return this;
}
public NewMeasureDto build() {
return new NewMeasureDto(this);
}
}
}
And request mapping in RestController:
#PostMapping(value="/new-measure-package") //addStation id
public ResponseEntity<Void> newMeasure(#RequestBody NewMeasurePackageDto measureList){
//if api key is valid
return measureService.saveMeasurePackage(measureList.getNewMeasureListDto()) ? new ResponseEntity<>(HttpStatus.OK) :
new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
With this code all I got is error about null measureList in Service function when trying to iterate over the list. I tried changing #RequestBody to
List<NewMeasureDto> measureList, and to Map<String, NewMeasureDto> measureList but still measureList is null or empty.
Thanks to ShaharT suggestion I found the answer.
There was missing setter in NewMeasurePackageDto, the class should look like this:
package com.weather.server.domain.dto;
import java.util.ArrayList;
public class NewMeasurePackageDto {
private ArrayList<NewMeasureDto> measureList;
public NewMeasurePackageDto(ArrayList<NewMeasureDto> measureList) {
this.measureList = measureList;
}
public NewMeasurePackageDto() {
}
public ArrayList<NewMeasureDto> getMeasureList() {
return measureList;
}
public void setMeasureList(ArrayList<NewMeasureDto> measureList) {
this.measureList = measureList;
}
#Override
public String toString() {
return "NewMeasurePackageDto{" +
"measureList=" + measureList +
'}';
}
}
Conclusion is: when dealing with object of arrays in JSON, there must be setter method for variable storing list in DTO.
{
"data": [
{
"id": 4,
"customer_id": 3,
"service_type_id": 1,
"full_name": "Teja Babu S",
"email": "testemail#gmail.com",
camera_types": 1,
"dvr_types": 1,
"created_at": "2020-01-04 14:18:30",
"updated_at": "2020-01-04 14:18:30",
"camera_type": {
"id": 1,
"name": "Analogue hd",
"description": null,
"status": 1,
"deleted_at": null,
"created_at": "2020-01-04 08:03:45",
"updated_at": "2020-01-04 08:54:23"
},
"dvr_type": {
"id": 1,
"name": "XVR - nvr",
"description": "desc",
"status": 1,
"deleted_at": null,
"created_at": "2020-01-04 08:28:04",
"updated_at": "2020-01-04 08:57:17"
}
}
]
}
I am using the http://www.jsonschema2pojo.org/ for converion. I am not pasting the result to keep the question simple.
package - package
com.tesmachino.saycure.entities.OrderHistory.OrderDetail;
ClassName - OrderDetailsResponse
Target language: Java
Source type: JSON
Annotation style: Moshi
I would like to access the Name from Both camera_type and dvr_type
I am using Moshi + retrofit
OrderDetail
package com.tesmachino.saycure;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.tesmachino.saycure.Auth.TokenManager;
import com.tesmachino.saycure.entities.OrderHistory.OrderDetail.OrderDetailsResponse;
import com.tesmachino.saycure.entities.OrderHistory.OrderHistoryResponse;
import com.tesmachino.saycure.entities.UserDetails.UserDetailsGetResponse;
import com.tesmachino.saycure.network.ApiService;
import com.tesmachino.saycure.network.RetrofitBuilder;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class OrderDetail extends AppCompatActivity {
ApiService service;
TokenManager tokenManager;
Call<OrderDetailsResponse> call;
private static final String TAG = "OrderDetail";
#BindView(R.id.orderdetails_id)
TextView orderId;
#BindView(R.id.orderdetails_client_name)
TextView orderDetailsClientName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_detail);
ButterKnife.bind(this);
tokenManager = TokenManager.getInstance(getSharedPreferences("prefs", MODE_PRIVATE));
service = RetrofitBuilder.createServiceWithAuth(ApiService.class, tokenManager);
}
#Override
protected void onResume() {
//Get the Data from the Intent
if (getIntent().hasExtra("order_id")) {
int order_id = getIntent().getIntExtra("order_id", 1);
Log.d(TAG, "IntentWorking" + order_id);
call = service.orderDetails(order_id);
call.enqueue(new Callback<OrderDetailsResponse>() {
#Override
public void onResponse(Call<OrderDetailsResponse> call, Response<OrderDetailsResponse> response) {
OrderDetailsResponse orderDetails = response.body();
if (orderDetails != null){
}
Log.w(TAG, "onResponse123: " + orderDetails.getData().get(0).getId());
Toast.makeText(OrderDetail.this, "" + response.body().toString(), Toast.LENGTH_SHORT).show();
orderId.setText(String.valueOf(orderDetails.getData().get(0).getId()));
orderDetailsClientName.setText(orderDetails.getData().get(0).getFullName());
Log.w(TAG, "onResponse45321: "+ orderDetails.getData().get(0).getCameraType());
}
#Override
public void onFailure(Call<OrderDetailsResponse> call, Throwable t) {
Log.w(TAG, "onFailure: " + t.getMessage());
Toast.makeText(OrderDetail.this, "Failure" + t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(this, "There seems to be an error while fetching the Order Id. Please Try Again", Toast.LENGTH_SHORT).show();
}
super.onResume();
}
}
OrderDetailsResponse
package com.tesmachino.saycure.entities.OrderHistory.OrderDetail;
import com.squareup.moshi.Json;
import org.apache.commons.lang3.builder.ToStringBuilder;
import java.util.List;
public class OrderDetailsResponse {
#Json(name = "data")
private List<OrderDetailsGet> data = null;
public List<OrderDetailsGet> getData() {
return data;
}
public void setData(List<OrderDetailsGet> data) {
this.data = data;
}
#Override
public String toString() {
return new ToStringBuilder(this).append("data", data).toString();
}
}
OrderDetailsGet
package com.tesmachino.saycure.entities.OrderHistory.OrderDetail;
import com.squareup.moshi.Json;
import org.apache.commons.lang3.builder.ToStringBuilder;
public class OrderDetailsGet {
#Json(name = "id")
private Integer id;
#Json(name = "customer_id")
private Integer customerId;
#Json(name = "service_type_id")
private Integer serviceTypeId;
#Json(name = "full_name")
private String fullName;
#Json(name = "email")
private String email;
#Json(name = "address_line_1")
private String addressLine1;
#Json(name = "address_line_2")
private String addressLine2;
#Json(name = "phone_no")
private String phoneNo;
#Json(name = "alternate_phone_no")
private Object alternatePhoneNo;
#Json(name = "land_mark")
private Object landMark;
#Json(name = "area")
private Object area;
#Json(name = "district")
private String district;
#Json(name = "city")
private String city;
#Json(name = "state")
private String state;
#Json(name = "pincode")
private Integer pincode;
#Json(name = "type_of_property")
private Integer typeOfProperty;
#Json(name = "camera_types")
private Integer cameraTypes;
#Json(name = "no_of_cameras")
private Integer noOfCameras;
#Json(name = "dvr_types")
private Integer dvrTypes;
#Json(name = "dvr_channel")
private Integer dvrChannel;
#Json(name = "notes")
private Object notes;
#Json(name = "deleted_at")
private Object deletedAt;
#Json(name = "created_at")
private String createdAt;
#Json(name = "updated_at")
private String updatedAt;
#Json(name = "camera_type")
private CameraType cameraType;
#Json(name = "dvr_type")
private DvrType dvrType;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getCustomerId() {
return customerId;
}
public void setCustomerId(Integer customerId) {
this.customerId = customerId;
}
public Integer getServiceTypeId() {
return serviceTypeId;
}
public void setServiceTypeId(Integer serviceTypeId) {
this.serviceTypeId = serviceTypeId;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddressLine1() {
return addressLine1;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
public String getAddressLine2() {
return addressLine2;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
public String getPhoneNo() {
return phoneNo;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
public Object getAlternatePhoneNo() {
return alternatePhoneNo;
}
public void setAlternatePhoneNo(Object alternatePhoneNo) {
this.alternatePhoneNo = alternatePhoneNo;
}
public Object getLandMark() {
return landMark;
}
public void setLandMark(Object landMark) {
this.landMark = landMark;
}
public Object getArea() {
return area;
}
public void setArea(Object area) {
this.area = area;
}
public String getDistrict() {
return district;
}
public void setDistrict(String district) {
this.district = district;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public Integer getPincode() {
return pincode;
}
public void setPincode(Integer pincode) {
this.pincode = pincode;
}
public Integer getTypeOfProperty() {
return typeOfProperty;
}
public void setTypeOfProperty(Integer typeOfProperty) {
this.typeOfProperty = typeOfProperty;
}
public Integer getCameraTypes() {
return cameraTypes;
}
public void setCameraTypes(Integer cameraTypes) {
this.cameraTypes = cameraTypes;
}
public Integer getNoOfCameras() {
return noOfCameras;
}
public void setNoOfCameras(Integer noOfCameras) {
this.noOfCameras = noOfCameras;
}
public Integer getDvrTypes() {
return dvrTypes;
}
public void setDvrTypes(Integer dvrTypes) {
this.dvrTypes = dvrTypes;
}
public Integer getDvrChannel() {
return dvrChannel;
}
public void setDvrChannel(Integer dvrChannel) {
this.dvrChannel = dvrChannel;
}
public Object getNotes() {
return notes;
}
public void setNotes(Object notes) {
this.notes = notes;
}
public Object getDeletedAt() {
return deletedAt;
}
public void setDeletedAt(Object deletedAt) {
this.deletedAt = deletedAt;
}
public String getCreatedAt() {
return createdAt;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
public String getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(String updatedAt) {
this.updatedAt = updatedAt;
}
public CameraType getCameraType() {
return cameraType;
}
public void setCameraType(CameraType cameraType) {
this.cameraType = cameraType;
}
public DvrType getDvrType() {
return dvrType;
}
public void setDvrType(DvrType dvrType) {
this.dvrType = dvrType;
}
#Override
public String toString() {
return new ToStringBuilder(this).append("id", id).append("customerId", customerId).append("serviceTypeId", serviceTypeId).append("fullName", fullName).append("email", email).append("addressLine1", addressLine1).append("addressLine2", addressLine2).append("phoneNo", phoneNo).append("alternatePhoneNo", alternatePhoneNo).append("landMark", landMark).append("area", area).append("district", district).append("city", city).append("state", state).append("pincode", pincode).append("typeOfProperty", typeOfProperty).append("cameraTypes", cameraTypes).append("noOfCameras", noOfCameras).append("dvrTypes", dvrTypes).append("dvrChannel", dvrChannel).append("notes", notes).append("deletedAt", deletedAt).append("createdAt", createdAt).append("updatedAt", updatedAt).append("cameraType", cameraType).append("dvrType", dvrType).toString();
}
}
If you are just trying to the the name from camera_type and dvr_type, you can do:
//This assumes that you have a getCameraType & getDvrTypes method in your OrderDetailsGet class
String camera_name = orderDetails.getData().get(0).getCameraType().getName()
String dvr_name = orderDetails.getData().get(0).getDvrTypes().getName()
Here is my response from database
{
"error": false,
"images": [
{
"id": "9",
"url": "http://192.168.1.27/BimbinganPA/include//uploads/9.png"
}
]
}
my response class UserDataResponse.java (edited full data response)
#SerializedName("error")
#Expose
private String iserror;
#SerializedName("error_msg")
#Expose
private String error_msg;
#SerializedName("nama")
#Expose
private String nama;
#SerializedName("nomor_induk")
#Expose
private String nomor_induk;
#SerializedName("prodi")
#Expose
private String prodi;
#SerializedName("dosen_pa")
#Expose
private String dosen_pa;
#SerializedName("email")
#Expose
private String email;
#SerializedName("email2")
#Expose
private String email2;
#SerializedName("mobile_phone")
#Expose
private String mobile_phone;
#SerializedName("mobile_phone2")
#Expose
private String mobile_phone2;
#SerializedName("alamat_mlg")
#Expose
private String alamat_mlg;
#SerializedName("alamat_asal")
#Expose
private String alamat_asal;
#SerializedName("sma_asal")
#Expose
private String sma_asal;
#SerializedName("hobby")
#Expose
private String hobby;
#SerializedName("ekskul")
#Expose
private String ekskul;
#SerializedName("nama_ortu")
#Expose
private String nama_ortu;
#SerializedName("alamat_ortu")
#Expose
private String alamat_ortu;
#SerializedName("email_ortu")
#Expose
private String email_ortu;
#SerializedName("mobilephone_ortu")
#Expose
private String mobilephone_ortu;
#SerializedName("id_fb")
#Expose
private String id_fb;
#SerializedName("id_ig")
#Expose
private String id_ig;
#SerializedName("id_line")
#Expose
private String id_line;
#SerializedName("numb_wa")
#Expose
private String numb_wa;
#SerializedName("images")
#Expose
private List<Image> images = null;
public String getIserror() {
return iserror;
}
public void setIserror(String iserror) {
this.iserror = iserror;
}
public String getMsg() {
return error_msg;
}
public void setMsg(String error_msg) {
this.error_msg = error_msg;
}
public String getNama() {
return nama;
}
public void setNama(String nama) {
this.nama = nama;
}
public String getNomor_induk() {
return nomor_induk;
}
public void setNomor_induk(String nomor_induk) {
this.nomor_induk = nomor_induk;
}
public String getProdi() {
return prodi;
}
public void setProdi(String prodi) {
this.prodi = prodi;
}
public String getDosen_pa() {
return dosen_pa;
}
public void setDosen_pa(String dosen_pa) {
this.dosen_pa = dosen_pa;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getEmail2() {
return email2;
}
public void setEmail2(String email2) {
this.email2 = email2;
}
public String getMobile_phone() {
return mobile_phone;
}
public void setMobile_phone(String mobile_phone) {
this.email = mobile_phone;
}
public String getMobile_phone2() {
return mobile_phone2;
}
public void setMobile_phone2(String mobile_phone2) {
this.email = mobile_phone2;
}
public String getAlamat_mlg() {
return alamat_mlg;
}
public void setAlamat_mlg(String alamat_mlg) {
this.alamat_mlg = alamat_mlg;
}
public String getAlamat_asal() {
return alamat_asal;
}
public void setAlamat_asal(String alamat_asal) {
this.alamat_asal = alamat_asal;
}
public String getSma_asal() {
return sma_asal;
}
public void setSma_asal(String sma_asal) {
this.sma_asal = sma_asal;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
public String getEkskul() {
return ekskul;
}
public void setEkskul(String ekskul) {
this.ekskul = ekskul;
}
public String getNama_ortu() {
return nama_ortu;
}
public void setNama_ortu(String nama_ortu) {
this.nama_ortu = nama_ortu;
}
public String getAlamat_ortu() {
return alamat_ortu;
}
public void setAlamat_ortu(String alamat_ortu) {
this.alamat_ortu = alamat_ortu;
}
public String getEmail_ortu() {
return email_ortu;
}
public void setEmail_ortu(String email_ortu) {
this.email_ortu = email_ortu;
}
public String getMobilephone_ortu() {
return mobilephone_ortu;
}
public void setMobilephone_ortu(String mobilephone_ortu) {
this.mobilephone_ortu = mobilephone_ortu;
}
public String getId_fb() {
return id_fb;
}
public void setId_fb(String id_fb) {
this.id_fb = id_fb;
}
public String getId_ig() {
return id_ig;
}
public void setId_ig(String id_ig) {
this.id_ig = id_ig;
}
public String getId_line() {
return id_line;
}
public void setId_line(String id_line) {
this.id_line = id_line;
}
public String getNumb_wa() {
return numb_wa;
}
public void setNumb_wa(String numb_wa) {
this.numb_wa = numb_wa;
}
public List<Image> getImages() {
return images;
}
here is my Image.class
#SerializedName("id")
#Expose
private String no_user_id;
#SerializedName("url")
#Expose
private String image_url;
public String getNo_user_id() {
return no_user_id;
}
public String getImage_url() {
return image_url;
}
this is how i call it
public void F0_getPhoto(){
Call<List<UserDataResponse>> getPhoto = mApiService.getImage(
String.valueOf(mPrefs.getUserID()));
getPhoto.enqueue(new Callback<List<UserDataResponse>>() {
#Override
public void onResponse(Call<List<UserDataResponse>> call, Response<List<UserDataResponse>>response) {
// String iserror = response.body().getIserror();
// Jika login berhasil maka data nama yang ada di response API
// akan diparsing ke activity selanjutnya.
List<UserDataResponse> userDatalist = response.body();
//Creating an String array for the ListView
String[] iserror = new String[userDatalist.size()];
//looping through all the heroes and inserting the names inside the string array
for (int i = 0; i < userDatalist.size(); i++) {
iserror[i] = userDatalist.get(i).getIserror();
if (iserror.equals("false")) {
String[] url = new String[userDatalist.size()];
url[i] = userDatalist.get(i).getImages().getimage_Url();
showPhoto(url);
}
}
#Override
public void onFailure(Call<List<UserDataResponse>> call, Throwable t){
Log.e("debug", "onFailure: ERROR > " + t.toString());
}
});
}
and my question is how i can call response "url" from array i tried to call method getimage_Url() after method getImage() but i cannot call it
url[i] = userDatalist.get(i).getImages().getimage_Url();
According your above json, it's return Object rather than Array. So, modify your F0_getPhoto to handle this.
public void F0_getPhoto(){
Call<UserDataResponse> getPhoto = mApiService.getImage(
String.valueOf(mPrefs.getUserID()));
getPhoto.enqueue(new Callback<UserDataResponse>() {
#Override
public void onResponse(Call<UserDataResponse> call, Response<UserDataResponse>response) {
// String iserror = response.body().getIserror();
// Jika login berhasil maka data nama yang ada di response API
// akan diparsing ke activity selanjutnya.
UserDataResponse userData = response.body();
//Creating an String array for the ListView
String error = userData.getIserror();
List<Image> images = userData.getImages();
String[] url = new String[images.size()];
//looping through all the heroes and inserting the names inside the string array
if (iserror.equals("false")) {
for (int i = 0; i < images.size(); i++) {
url[i] = images.getimage_Url();
}
showPhoto(url);
}
#Override
public void onFailure(Call<UserDataResponse> call, Throwable t){
Log.e("debug", "onFailure: ERROR > " + t.toString());
}
});
}
}
I'm trying to make a simple weather app. I'm using this API for it. on that same page is a list of parameters in the JSON response. I can search for all the parameters and get a response except for the 'weather' parameter. every time I try that I get an
java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 3 path $[0]
error. I'm not sure what's causing it. here's my code.
public class Weather {
private String city;
private OWM owm = new OWM("8984d739fa91d7031fff0e84a3d2c520");
private CurrentWeather currentWeather;
private String weather;
private Clouds cloud;
public Weather() throws APIException {
String API_KEY = "8984d739fa91d7031fff0e84a3d2c520";
String Location = "Brooklyn";
String urlString = "http://api.openweathermap.org/data/2.5/weather?q=" + Location
+ "&appid=" + API_KEY + "&units=imperial";
try {
StringBuilder result = new StringBuilder();
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null){
result.append(line);
}
rd.close();
System.out.println(result);
Map<String, Object> respMap = jsonToMap(result.toString());
Map<String, Object> mainMap = jsonToMap(respMap.get("main").toString());
Map<String, Object> windMap = jsonToMap(respMap.get("wind").toString());
Map<String, Object> cloudsMap = jsonToMap(respMap.get("weather").toString());
// error is here
System.out.println("Current Temperature: " + mainMap.get("temp"));
System.out.println("current humidity " + mainMap.get("humidity"));
System.out.println("clouds " + respMap.get("description"));
// System.out.println("weather conditions: " + cloudsMap.get("main"));
// this always returns null
System.out.println("wind speeds " + windMap.get("speed"));
System.out.println("wind angle: " + windMap.get("deg"));
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static Map<String, Object> jsonToMap(String str){
Map<String, Object> map = new Gson().fromJson(
str, new TypeToken<HashMap<String, Object>>() {}.getType()
);
return map;
}
public String getCityName() {
return cityName;
}
public int getCurrentWeather() throws APIException {
owm.setUnit(OWM.Unit.IMPERIAL);
currentWeather = owm.currentWeatherByCityName(this.cityName);
return (int) Math.round(currentWeather.getMainData().getTemp());
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public void setZipCode(String zipCode){
this.zipCode = zipCode;
}
public String getZipCode(){
return this.zipCode;
}
public String getWeather(){
return this.weather;
}
}
I'm not really sure why that one parameter isn't working. I can search anything else fine, so why can't I search the weather parameter?
Edit:
I'm doing this in my try/catch statement. it's giving me a NullPointerException
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
conn.connect();
JsonParser jp = new JsonParser();
JsonElement root = jp.parse(new InputStreamReader((InputStream) conn.getContent()));
JsonObject rootObj = root.getAsJsonObject();
String description = rootObj.get("weather").getAsString();
// name of the array in the json
System.out.println(description);
Instead of blindly considering Hashmap for keyvalues, consider creating pojos, and then parse it.
Create all PoJo for json.
Main.java
public class Weather {
public static void main(String[] args) {
String API_KEY = "8984d739fa91d7031fff0e84a3d2c520";
String Location = "Brooklyn";
String urlString = "http://api.openweathermap.org/data/2.5/weather?q=" + Location
+ "&appid=" + API_KEY + "&units=imperial";
try {
StringBuilder result = new StringBuilder();
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null){
result.append(line);
}
rd.close();
System.out.println(result);
com.google.gson.Gson gson=new Gson();
Example finalResult=gson.fromJson(result.toString() , Example.class);
System.out.println(finalResult.getMain().getTemp()); //56.26
System.out.println(finalResult.getMain().getHumidity()); // 54
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Example.java (This pojo is for your json schema)
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("coord")
#Expose
private Coord coord;
#SerializedName("weather")
#Expose
private List<Weather> weather = null;
#SerializedName("base")
#Expose
private String base;
#SerializedName("main")
#Expose
private Main main;
#SerializedName("visibility")
#Expose
private Integer visibility;
#SerializedName("wind")
#Expose
private Wind wind;
#SerializedName("clouds")
#Expose
private Clouds clouds;
#SerializedName("dt")
#Expose
private Integer dt;
#SerializedName("sys")
#Expose
private Sys sys;
#SerializedName("timezone")
#Expose
private Integer timezone;
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("cod")
#Expose
private Integer cod;
public Coord getCoord() {
return coord;
}
public void setCoord(Coord coord) {
this.coord = coord;
}
public List<Weather> getWeather() {
return weather;
}
public void setWeather(List<Weather> weather) {
this.weather = weather;
}
public String getBase() {
return base;
}
public void setBase(String base) {
this.base = base;
}
public Main getMain() {
return main;
}
public void setMain(Main main) {
this.main = main;
}
public Integer getVisibility() {
return visibility;
}
public void setVisibility(Integer visibility) {
this.visibility = visibility;
}
public Wind getWind() {
return wind;
}
public void setWind(Wind wind) {
this.wind = wind;
}
public Clouds getClouds() {
return clouds;
}
public void setClouds(Clouds clouds) {
this.clouds = clouds;
}
public Integer getDt() {
return dt;
}
public void setDt(Integer dt) {
this.dt = dt;
}
public Sys getSys() {
return sys;
}
public void setSys(Sys sys) {
this.sys = sys;
}
public Integer getTimezone() {
return timezone;
}
public void setTimezone(Integer timezone) {
this.timezone = timezone;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getCod() {
return cod;
}
public void setCod(Integer cod) {
this.cod = cod;
}
}
Coord.java
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Coord {
#SerializedName("lon")
#Expose
private Double lon;
#SerializedName("lat")
#Expose
private Double lat;
public Double getLon() {
return lon;
}
public void setLon(Double lon) {
this.lon = lon;
}
public Double getLat() {
return lat;
}
public void setLat(Double lat) {
this.lat = lat;
}
}
Weather.java
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Weather {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("main")
#Expose
private String main;
#SerializedName("description")
#Expose
private String description;
#SerializedName("icon")
#Expose
private String icon;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getMain() {
return main;
}
public void setMain(String main) {
this.main = main;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
}
Main.java
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Main {
#SerializedName("temp")
#Expose
private Double temp;
#SerializedName("pressure")
#Expose
private Integer pressure;
#SerializedName("humidity")
#Expose
private Integer humidity;
#SerializedName("temp_min")
#Expose
private Integer tempMin;
#SerializedName("temp_max")
#Expose
private Double tempMax;
public Double getTemp() {
return temp;
}
public void setTemp(Double temp) {
this.temp = temp;
}
public Integer getPressure() {
return pressure;
}
public void setPressure(Integer pressure) {
this.pressure = pressure;
}
public Integer getHumidity() {
return humidity;
}
public void setHumidity(Integer humidity) {
this.humidity = humidity;
}
public Integer getTempMin() {
return tempMin;
}
public void setTempMin(Integer tempMin) {
this.tempMin = tempMin;
}
public Double getTempMax() {
return tempMax;
}
public void setTempMax(Double tempMax) {
this.tempMax = tempMax;
}
}
Wind.java
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Wind {
#SerializedName("speed")
#Expose
private Double speed;
#SerializedName("deg")
#Expose
private Integer deg;
public Double getSpeed() {
return speed;
}
public void setSpeed(Double speed) {
this.speed = speed;
}
public Integer getDeg() {
return deg;
}
public void setDeg(Integer deg) {
this.deg = deg;
}
}
Clouds.java
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Clouds {
#SerializedName("all")
#Expose
private Integer all;
public Integer getAll() {
return all;
}
public void setAll(Integer all) {
this.all = all;
}
}
Sys.java
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Sys {
#SerializedName("type")
#Expose
private Integer type;
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("message")
#Expose
private Double message;
#SerializedName("country")
#Expose
private String country;
#SerializedName("sunrise")
#Expose
private Integer sunrise;
#SerializedName("sunset")
#Expose
private Integer sunset;
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Double getMessage() {
return message;
}
public void setMessage(Double message) {
this.message = message;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public Integer getSunrise() {
return sunrise;
}
public void setSunrise(Integer sunrise) {
this.sunrise = sunrise;
}
public Integer getSunset() {
return sunset;
}
public void setSunset(Integer sunset) {
this.sunset = sunset;
}
}
Map<String, Object> cloudsMap = jsonToMap(respMap.get("weather").toString());
This is the problem. You're trying to parse the weather property of the response as an object (a Map) but it's actually an array.
The best way to parse the Json here is Gson Library
Here first you can create pojo class of response you getting ,after that just pass the response String and get your output.
Gson gson=new Gson();
YourClass result=gson.fromjson(jsonString , YourClass.class);
How can I use GSON to parse the following JSON object:
{
"ProductsByCategory": [
{.....},
{.....},
{.....},
{.....},
]
}
The JSON object contains an array of elements. I am using GSON to try and parse the JSON and have the following POJO classes to assist me with this.
public class ProductItems {
#SerializedName("ProductsByCategory")
#Expose
private List<ProductsByCategory> productsByCategory = null;
public List<ProductsByCategory> getProductsByCategory() {
return productsByCategory;
}
public void setProductsByCategory(List<ProductsByCategory> productsByCategory) {
this.productsByCategory = productsByCategory;
}
}
public class ProductsByCategory {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("slug")
#Expose
private String slug;
#SerializedName("permalink")
#Expose
private String permalink;
#SerializedName("date_created")
#Expose
private String dateCreated;
#SerializedName("date_created_gmt")
#Expose
private String dateCreatedGmt;
#SerializedName("date_modified")
#Expose
private String dateModified;
#SerializedName("date_modified_gmt")
#Expose
private String dateModifiedGmt;
#SerializedName("type")
#Expose
private String type;
#SerializedName("status")
#Expose
private String status;
#SerializedName("featured")
#Expose
private Boolean featured;
#SerializedName("catalog_visibility")
#Expose
private String catalogVisibility;
#SerializedName("description")
#Expose
private String description;
#SerializedName("short_description")
#Expose
private String shortDescription;
#SerializedName("sku")
#Expose
private String sku;
#SerializedName("price")
#Expose
private String price;
#SerializedName("regular_price")
#Expose
private String regularPrice;
#SerializedName("sale_price")
#Expose
private String salePrice;
#SerializedName("date_on_sale_from")
#Expose
private Object dateOnSaleFrom;
#SerializedName("date_on_sale_from_gmt")
#Expose
private Object dateOnSaleFromGmt;
#SerializedName("date_on_sale_to")
#Expose
private Object dateOnSaleTo;
#SerializedName("date_on_sale_to_gmt")
#Expose
private Object dateOnSaleToGmt;
#SerializedName("price_html")
#Expose
private String priceHtml;
#SerializedName("on_sale")
#Expose
private Boolean onSale;
#SerializedName("purchasable")
#Expose
private Boolean purchasable;
#SerializedName("total_sales")
#Expose
private Integer totalSales;
#SerializedName("virtual")
#Expose
private Boolean virtual;
#SerializedName("downloadable")
#Expose
private Boolean downloadable;
#SerializedName("downloads")
#Expose
private List<Object> downloads = null;
#SerializedName("download_limit")
#Expose
private Integer downloadLimit;
#SerializedName("download_expiry")
#Expose
private Integer downloadExpiry;
#SerializedName("external_url")
#Expose
private String externalUrl;
#SerializedName("button_text")
#Expose
private String buttonText;
#SerializedName("tax_status")
#Expose
private String taxStatus;
#SerializedName("tax_class")
#Expose
private String taxClass;
#SerializedName("manage_stock")
#Expose
private Boolean manageStock;
#SerializedName("stock_quantity")
#Expose
private Integer stockQuantity;
#SerializedName("in_stock")
#Expose
private Boolean inStock;
#SerializedName("backorders")
#Expose
private String backorders;
#SerializedName("backorders_allowed")
#Expose
private Boolean backordersAllowed;
#SerializedName("backordered")
#Expose
private Boolean backordered;
#SerializedName("sold_individually")
#Expose
private Boolean soldIndividually;
#SerializedName("weight")
#Expose
private String weight;
#SerializedName("dimensions")
#Expose
private Dimensions dimensions;
#SerializedName("shipping_required")
#Expose
private Boolean shippingRequired;
#SerializedName("shipping_taxable")
#Expose
private Boolean shippingTaxable;
#SerializedName("shipping_class")
#Expose
private String shippingClass;
#SerializedName("shipping_class_id")
#Expose
private Integer shippingClassId;
#SerializedName("reviews_allowed")
#Expose
private Boolean reviewsAllowed;
#SerializedName("average_rating")
#Expose
private String averageRating;
#SerializedName("rating_count")
#Expose
private Integer ratingCount;
#SerializedName("related_ids")
#Expose
private List<Integer> relatedIds = null;
#SerializedName("upsell_ids")
#Expose
private List<Object> upsellIds = null;
#SerializedName("cross_sell_ids")
#Expose
private List<Object> crossSellIds = null;
#SerializedName("parent_id")
#Expose
private Integer parentId;
#SerializedName("purchase_note")
#Expose
private String purchaseNote;
#SerializedName("categories")
#Expose
private List<Category> categories = null;
#SerializedName("tags")
#Expose
private List<Object> tags = null;
#SerializedName("images")
#Expose
private List<Image> images = null;
#SerializedName("attributes")
#Expose
private List<Attribute> attributes = null;
#SerializedName("default_attributes")
#Expose
private List<Object> defaultAttributes = null;
#SerializedName("variations")
#Expose
private List<Integer> variations = null;
#SerializedName("grouped_products")
#Expose
private List<Object> groupedProducts = null;
#SerializedName("menu_order")
#Expose
private Integer menuOrder;
#SerializedName("meta_data")
#Expose
private List<MetaDatum> metaData = null;
#SerializedName("_links")
#Expose
private Links links;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSlug() {
return slug;
}
public void setSlug(String slug) {
this.slug = slug;
}
public String getPermalink() {
return permalink;
}
public void setPermalink(String permalink) {
this.permalink = permalink;
}
public String getDateCreated() {
return dateCreated;
}
public void setDateCreated(String dateCreated) {
this.dateCreated = dateCreated;
}
public String getDateCreatedGmt() {
return dateCreatedGmt;
}
public void setDateCreatedGmt(String dateCreatedGmt) {
this.dateCreatedGmt = dateCreatedGmt;
}
public String getDateModified() {
return dateModified;
}
public void setDateModified(String dateModified) {
this.dateModified = dateModified;
}
public String getDateModifiedGmt() {
return dateModifiedGmt;
}
public void setDateModifiedGmt(String dateModifiedGmt) {
this.dateModifiedGmt = dateModifiedGmt;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Boolean getFeatured() {
return featured;
}
public void setFeatured(Boolean featured) {
this.featured = featured;
}
public String getCatalogVisibility() {
return catalogVisibility;
}
public void setCatalogVisibility(String catalogVisibility) {
this.catalogVisibility = catalogVisibility;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getShortDescription() {
return shortDescription;
}
public void setShortDescription(String shortDescription) {
this.shortDescription = shortDescription;
}
public String getSku() {
return sku;
}
public void setSku(String sku) {
this.sku = sku;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getRegularPrice() {
return regularPrice;
}
public void setRegularPrice(String regularPrice) {
this.regularPrice = regularPrice;
}
public String getSalePrice() {
return salePrice;
}
public void setSalePrice(String salePrice) {
this.salePrice = salePrice;
}
public Object getDateOnSaleFrom() {
return dateOnSaleFrom;
}
public void setDateOnSaleFrom(Object dateOnSaleFrom) {
this.dateOnSaleFrom = dateOnSaleFrom;
}
public Object getDateOnSaleFromGmt() {
return dateOnSaleFromGmt;
}
public void setDateOnSaleFromGmt(Object dateOnSaleFromGmt) {
this.dateOnSaleFromGmt = dateOnSaleFromGmt;
}
public Object getDateOnSaleTo() {
return dateOnSaleTo;
}
public void setDateOnSaleTo(Object dateOnSaleTo) {
this.dateOnSaleTo = dateOnSaleTo;
}
public Object getDateOnSaleToGmt() {
return dateOnSaleToGmt;
}
public void setDateOnSaleToGmt(Object dateOnSaleToGmt) {
this.dateOnSaleToGmt = dateOnSaleToGmt;
}
public String getPriceHtml() {
return priceHtml;
}
public void setPriceHtml(String priceHtml) {
this.priceHtml = priceHtml;
}
public Boolean getOnSale() {
return onSale;
}
public void setOnSale(Boolean onSale) {
this.onSale = onSale;
}
public Boolean getPurchasable() {
return purchasable;
}
public void setPurchasable(Boolean purchasable) {
this.purchasable = purchasable;
}
public Integer getTotalSales() {
return totalSales;
}
public void setTotalSales(Integer totalSales) {
this.totalSales = totalSales;
}
public Boolean getVirtual() {
return virtual;
}
public void setVirtual(Boolean virtual) {
this.virtual = virtual;
}
public Boolean getDownloadable() {
return downloadable;
}
public void setDownloadable(Boolean downloadable) {
this.downloadable = downloadable;
}
public List<Object> getDownloads() {
return downloads;
}
public void setDownloads(List<Object> downloads) {
this.downloads = downloads;
}
public Integer getDownloadLimit() {
return downloadLimit;
}
public void setDownloadLimit(Integer downloadLimit) {
this.downloadLimit = downloadLimit;
}
public Integer getDownloadExpiry() {
return downloadExpiry;
}
public void setDownloadExpiry(Integer downloadExpiry) {
this.downloadExpiry = downloadExpiry;
}
public String getExternalUrl() {
return externalUrl;
}
public void setExternalUrl(String externalUrl) {
this.externalUrl = externalUrl;
}
public String getButtonText() {
return buttonText;
}
public void setButtonText(String buttonText) {
this.buttonText = buttonText;
}
public String getTaxStatus() {
return taxStatus;
}
public void setTaxStatus(String taxStatus) {
this.taxStatus = taxStatus;
}
public String getTaxClass() {
return taxClass;
}
public void setTaxClass(String taxClass) {
this.taxClass = taxClass;
}
public Boolean getManageStock() {
return manageStock;
}
public void setManageStock(Boolean manageStock) {
this.manageStock = manageStock;
}
public Integer getStockQuantity() {
return stockQuantity;
}
public void setStockQuantity(Integer stockQuantity) {
this.stockQuantity = stockQuantity;
}
public Boolean getInStock() {
return inStock;
}
public void setInStock(Boolean inStock) {
this.inStock = inStock;
}
public String getBackorders() {
return backorders;
}
public void setBackorders(String backorders) {
this.backorders = backorders;
}
public Boolean getBackordersAllowed() {
return backordersAllowed;
}
public void setBackordersAllowed(Boolean backordersAllowed) {
this.backordersAllowed = backordersAllowed;
}
public Boolean getBackordered() {
return backordered;
}
public void setBackordered(Boolean backordered) {
this.backordered = backordered;
}
public Boolean getSoldIndividually() {
return soldIndividually;
}
public void setSoldIndividually(Boolean soldIndividually) {
this.soldIndividually = soldIndividually;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public Dimensions getDimensions() {
return dimensions;
}
public void setDimensions(Dimensions dimensions) {
this.dimensions = dimensions;
}
public Boolean getShippingRequired() {
return shippingRequired;
}
public void setShippingRequired(Boolean shippingRequired) {
this.shippingRequired = shippingRequired;
}
public Boolean getShippingTaxable() {
return shippingTaxable;
}
public void setShippingTaxable(Boolean shippingTaxable) {
this.shippingTaxable = shippingTaxable;
}
public String getShippingClass() {
return shippingClass;
}
public void setShippingClass(String shippingClass) {
this.shippingClass = shippingClass;
}
public Integer getShippingClassId() {
return shippingClassId;
}
public void setShippingClassId(Integer shippingClassId) {
this.shippingClassId = shippingClassId;
}
public Boolean getReviewsAllowed() {
return reviewsAllowed;
}
public void setReviewsAllowed(Boolean reviewsAllowed) {
this.reviewsAllowed = reviewsAllowed;
}
public String getAverageRating() {
return averageRating;
}
public void setAverageRating(String averageRating) {
this.averageRating = averageRating;
}
public Integer getRatingCount() {
return ratingCount;
}
public void setRatingCount(Integer ratingCount) {
this.ratingCount = ratingCount;
}
public List<Integer> getRelatedIds() {
return relatedIds;
}
public void setRelatedIds(List<Integer> relatedIds) {
this.relatedIds = relatedIds;
}
public List<Object> getUpsellIds() {
return upsellIds;
}
public void setUpsellIds(List<Object> upsellIds) {
this.upsellIds = upsellIds;
}
public List<Object> getCrossSellIds() {
return crossSellIds;
}
public void setCrossSellIds(List<Object> crossSellIds) {
this.crossSellIds = crossSellIds;
}
public Integer getParentId() {
return parentId;
}
public void setParentId(Integer parentId) {
this.parentId = parentId;
}
public String getPurchaseNote() {
return purchaseNote;
}
public void setPurchaseNote(String purchaseNote) {
this.purchaseNote = purchaseNote;
}
public List<Category> getCategories() {
return categories;
}
public void setCategories(List<Category> categories) {
this.categories = categories;
}
public List<Object> getTags() {
return tags;
}
public void setTags(List<Object> tags) {
this.tags = tags;
}
public List<Image> getImages() {
return images;
}
public void setImages(List<Image> images) {
this.images = images;
}
public List<Attribute> getAttributes() {
return attributes;
}
public void setAttributes(List<Attribute> attributes) {
this.attributes = attributes;
}
public List<Object> getDefaultAttributes() {
return defaultAttributes;
}
public void setDefaultAttributes(List<Object> defaultAttributes) {
this.defaultAttributes = defaultAttributes;
}
public List<Integer> getVariations() {
return variations;
}
public void setVariations(List<Integer> variations) {
this.variations = variations;
}
public List<Object> getGroupedProducts() {
return groupedProducts;
}
public void setGroupedProducts(List<Object> groupedProducts) {
this.groupedProducts = groupedProducts;
}
public Integer getMenuOrder() {
return menuOrder;
}
public void setMenuOrder(Integer menuOrder) {
this.menuOrder = menuOrder;
}
public List<MetaDatum> getMetaData() {
return metaData;
}
public void setMetaData(List<MetaDatum> metaData) {
this.metaData = metaData;
}
public Links getLinks() {
return links;
}
public void setLinks(Links links) {
this.links = links;
}
}
The code that I use is the following:
public void onResponse(Call call, Response response) throws IOException
{
String mMessage = response.body().string();
if (response.isSuccessful())
{
try
{
Gson gson = new Gson();
final ProductItems categoryProducts = gson.fromJson(mMessage, ProductItems.class);
response.close();
}
catch (Exception e)
{
Log.e("Error", "Failed to upload");
e.printStackTrace();
}
However, I get the following error: GSON throwing “Expected BEGIN_OBJECT but was BEGIN_ARRAY.
I have tried to change the ProductItems class to taking an object for productbycategories but then I get the following error: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 2324 path $.ProductsByCategory[0].meta_data[0].value. I am now a bit confused.
The reason you get this error is that the data is not consistent with the way the POJO is generated.
This is the specific part of the data that has the issue:
"meta_data": [
{
"id": 14232,
"key": "_vc_post_settings",
"value": {
"vc_grid_id": []
}
},
{
"id": 14273,
"key": "fb_product_description",
"value": ""
},
{
"id": 14274,
"key": "fb_visibility",
"value": "1"
},
Notice how the "meta_data" field is an array of objects and that these objects contain a "value" field. The data type of the "value" varies- sometimes it's an object and other times it's a string.
One possible solution would be to change the MetaDatum class so that the value is an Object:
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class MetaDatum {
...
#SerializedName("value")
#Expose
private Object value;
...
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
}