Saturday, 16 March 2019

Working with JSONArray


JSONArray is used to define ordered sequence of values.

Example
JSONArray jsonArray = new JSONArray();
Employee emp1 = new Employee(1, "Krishna", "ABC Corporation");
Employee emp2 = new Employee(2, "Rama", "XYZ Corporation");
Employee emp3 = new Employee(3, "Chamu", "TUV Corporation");

jsonArray.put(new JSONObject(emp1));
jsonArray.put(new JSONObject(emp2));
jsonArray.put(new JSONObject(emp3));

Above snippet generates below json array.

[{
         "organization": "ABC Corporation",
         "name": "Krishna",
         "id": 1
}, {
         "organization": "XYZ Corporation",
         "name": "Rama",
         "id": 2
}, {
         "organization": "TUV Corporation",
         "name": "Chamu",
         "id": 3
}]

App.java
package com.sample;

import org.json.JSONArray;
import org.json.JSONObject;

public class App {

 public static void main(String args[]) {
  JSONArray jsonArray = new JSONArray();
  
  Employee emp1 = new Employee(1, "Krishna", "ABC Corporation");
  Employee emp2 = new Employee(2, "Rama", "XYZ Corporation");
  Employee emp3 = new Employee(3, "Chamu", "TUV Corporation");
  
  jsonArray.put(new JSONObject(emp1));
  jsonArray.put(new JSONObject(emp2));
  jsonArray.put(new JSONObject(emp3));

  System.out.println(jsonArray);

 }
}




Previous                                                 Next                                                 Home

No comments:

Post a Comment