Shifat
Shifat

Reputation: 762

Reading data from JSON

Here is my JSON response

{
  "data": [
    {
      "id": "txn_17pHAkI4mX5ntfze4If5wIxW",
      "source": "tr_17pHAkI4mX5ntfzeIfNucubD",
      "amount": -100000,
      "currency": "usd",


    },
    {
      "id": "txn_17pH21I4mX5ntfzesrhdZwyf",
      "source": "tr_17pH21I4mX5ntfzeKLd0SWw0",
      "amount": -100000,

    },
    {
      "id": "txn_17pGVRI4mX5ntfzeBQPCWZZg",
      "source": "tr_17pGVRI4mX5ntfzegJNe1r4o",
      "amount": -100000,
      "currency": "usd"  
    }
  ],

  },
  "url": "/v1/balance/history",
  "count": null
}

I want to get "amount" and "id" from these three list. How to do it in java?

Upvotes: 0

Views: 52

Answers (1)

Matthew Wright
Matthew Wright

Reputation: 1525

Look into Google's Gson.

You need to create a class that represents the json data.

class Response {
    class Data {
        public String id;
        public String source;
        public int amount;
        public String currency;
    }
    public Data[] data;
    public String url;
    public int count;
}

Then read the data into a variable.

String json = "your json here";
Gson gson = new Gson();
Response response = gson.fromJson(json, Response.class);
for(Data d : response.data) {
    System.out.println(d.id);
    System.out.println(d.amount);
}

Upvotes: 2

Related Questions