Reputation: 2126
I have a stack with parsing JSON object in Android.
Here my JSON Data,
{
STATUS: "200"
ERROR: "false"
SECRETKEY: "deb1d0b9a70a0ed682d2975b2a583c28"
DATA: {
stock: 2
pins: [1]
0: {
id: "1"
pin: "8172310874"
serial: "0000000000100000"
card_type: "10000"
company: "FWIFI"
expiry_date: "2016-01-01"
invoice_id: "INVHQ/000001"
order_id: "1"
delivered: "0"
}
}
}
Here my parsing json object
try {
JSONObject json = new JSONObject(value);
String secretKey = json.get("SECRETKEY").toString();
JSONObject data_obj = new JSONObject("DATA"); //problem is here. It's go to catch block
JSONArray j_array = data_obj.getJSONArray("pins");
Integer qty = j_array.length();
for(int i = 0 ; i < j_array.length() ; i++){
//here loop
}
}catch (JSONException e) {
e.printStackTrace();
}
Please pointing me how can I loop? I change this. But, error say like that.
Value DATA of type java.lang.String cannot be converted to JSONObject
Upvotes: 1
Views: 285
Reputation: 1215
that's not a valid JSON ;)
After the key-value you need a comma and the keys have to be into declared into "..."
You can check if your JSON is valid on JSONLint, an online validator.
Basically it should look like:
{
"STATUS": 200,
"ERROR": "false",
"SECRETKEY": "deb1d0b9a70a0ed682d2975b2a583c28",
"DATA": {
"0": {
"id": "1",
"pin": "8172310874",
"serial": "0000000000100000",
"card_type": "10000",
"company": "FWIFI",
"expiry_date": "2016-01-01",
"invoice_id": "INVHQ/000001",
"order_id": "1",
"delivered": "0"
},
"stock": 2,
"pins": [
1
]
}
}
As soon as you have got something like that you can use GSON, Jackson or the standard JSONObject provided by android in order to access your JSON fields, objects and arrays as map through the keys that you have got in your JSON ("STATUS", "ERROR",...).
Upvotes: 1
Reputation: 1513
try this
try {
JSONObject json = new JSONObject(value);
String secretKey = json.get("SECRETKEY").toString();
JSONArray pin_Arr = json.getJSONArray("DATA"); //problem is here. It's go to catch blcok
Integer qty = pin_Arr.length();
for(int i = 0 ; i < pin_Arr.length() ; i++){
JSONObject actor = pin_Arr.getJSONObject(i);
String name = actor.getString("your data");
// you can add your datahere
}
}catch (JSONException e) {
e.printStackTrace();
}
Upvotes: 2
Reputation: 45
try : http://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple
Upvotes: 0
Reputation: 12042
Data is not a jsonarray it is a jsonObject {
->represent the jsonObject and [
->represents the jsonArray.so change toJSONObject pin_Arr = json.getJSONObject("DATA");
Upvotes: 2
Reputation: 2851
You should get that DATA
as a JSONObject
and then get your 0
in turn as a JSONObject.
Upvotes: 2