Working with JSON objects in Java

Last Updated On Sunday 3rd Oct 2021

Json Array Java

When accessing an API or similar to obtain information, the response may come into the form of JSON.

  • Receive response
  • Convert response string to JSON object
  • Parse JSON object

jsonarray java

	[
  {
    "id": 1,
    "name": "post1",
    "created_at": "2021-06-24T12:25:52.000Z",
    "updated_at": "2021-06-24T12:25:52.000Z"
  },
  {
    "id": 2,
    "name": "post2",
    "created_at": "2021-06-24T12:26:05.000Z",
    "updated_at": "2021-06-24T12:26:05.000Z"
  }
]
	

Convert response strings to JSON objects

getjsonarray java

	JSONArray jsonArray = new JSONArray(responseJSON);
	

Parse json objects and log the name attribute of a record

	for (int i = 0; i < jsonArray.length(); i++) {
  JSONObject jsonObject = jsonArray.getJSONObject(i);
  String value = jsonLineItem.getString("name");
  ....
}
	

jsonarray java example

	JSONArray dataaa = new JSONArray(Arrays.asList(new JSONObject(
        new HashMap() {
            {
                put("adam", 11);
                put("broad", 22);
            }
        }
    ),
    new JSONObject(
        new HashMap() {
            {
                put("adam", 33);
                put("broad", 44);
            }
        }
    )));
	

convert to List JSONObject

	  List<JSONObject> items = IntStream.range(0, dataaa.length())
            .mapToObj(index -> (JSONObject) dataaa.get(index))
            .collect(Collectors.toList());
	

Access the array elements now

	items.forEach(each -> System.out.println(each.get("adam"))); // 11 33