android studio JsonParser not a JSON Object
I'm put woocommerce coupons to an array list:
global $woocommerce;
$wc_coupon = new WC_Coupon($_GET['code']);
$name = $wc_coupon->get_code();
$amount = $wc_coupon->amount;
$usage_limit = $wc_coupon->usage_limit;
$usage_count = $wc_coupon->usage_count;
$coupons = array();
$coupon['name'] = $name;
$coupon['amount'] = $amount;
$coupon['usage_limit'] = $usage_limit;
$coupon['usage_count'] = $usage_count;
$coupons[] = $coupon;
output:
[{"name":"test","amount":"500","usage_limit":0,"usage_count":0}]
and in android studio I'm trying to fetch the amount:
URL url = new URL(sURL);
URLConnection request = url.openConnection();
request.connect();
JsonParser jp = new JsonParser(); //from gson
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent()));
JsonObject rootobj = root.getAsJsonObject();
coupon_price = rootobj.get("amount").getAsString();
And got this error:
Not a JSON Object: [{"name":"","amount":"0","usage_limit":0,"usage_count":0}]
The error message is telling you that the json you are trying to parse as an object is not one, it's an array.
Json objects are enclosed in curly braces like this {}
Json arrays are enclosed in square braces like this []