SRM
SRM

Reputation: 35

How to get the json array

I want the array of custac from the given json data. But I dont know how to call custac from that. I want to get the custac values in an array. can anyone help Here is my code

ArrayList<CustomerPayment> customerPayments = new 
ArrayList<CustomerPayment>();
try {
    JSONArray resultVal = response.getJSONArray("Data");

    int count=resultVal.length();
    for(int i=0;i<count;i++)
    {
        CustomerPayment payment = new CustomerPayment(resultVal.getJSONObject(i));
        customerPayments.add(payment);
    }
} catch (JSONException e) {
    e.printStackTrace();
}

Here is my jsondata

Result: {
    "Result": {
        "Status": 200,
        "Success": true,
        "Reason": "OK"
    },
    "Data": [
        {
            "CustomerID": "PTM_103",
            "FirstName": "Dhanya",
            "LastName": "Jacob ",
            "NickName": "",
            "FundAmount": 440,
            "custac": [
                {
                    "AccountTrackingId": "prod_4",
                    "ReferenceID": "",
                    "CustomerID": "PTM_103",
                    "OrderID": "ae3208287743908eb8e5911d8e7e73df",
                    "orderAmount": "0",
                    "CreatedAt": "prod"
                }
            ]
    },
    ...

Upvotes: 0

Views: 112

Answers (3)

Sniffer
Sniffer

Reputation: 1595

Try This Code

JSONArray custac;
 try {

    JSONArray resultVal = jsonObject.getJSONArray("Data");
    for (int i = 0; i < resultVal.length() - 1; i++) {
        jsonObject = resultVal.getJSONObject(i);
        custac = jsonObject.getJSONArray("custac");

        Log.d("TAG, custac + "");
    }
} catch (JSONException e) {
    e.printStackTrace();
}

Upvotes: 0

Sushant Paudel
Sushant Paudel

Reputation: 106

JSON data are objects parsed into a string for mostly NoSQL purposes and they can be parsed into objects. Gson is one of the libraries which is easy to use to parse your JSON data.

If you get jsonData as the response string which has Data, the following code can parse the custac in the list of array. But, firstly you have to create an object for Data

Data[] dataCollection = new Gson().fromJson(json,Data[].class);

Data must contain the attributes like CustomerID, FirstName, etc.

For your case,

class Data{
    private String CustomerID;
    private String FirstName;
    private String LastName;
    private String NickName;
    private int FundAmount;
    private ArrayList<Custac> custac;
    class Custac{
        // Write your attributes as shown above.
    }
}

Upvotes: 0

Mohammed Mahmoud
Mohammed Mahmoud

Reputation: 1148

you have to make something like this

JSONObject jsonObject = new JSONObject(response);

JSONArray resultVal = jsonObject.getJSONArray("Data");

Upvotes: 1

Related Questions