Saturday 16 March 2019

Produce JSONArray of json object from comma separated string


Step 1: Create a string such that comma separated headers followed by comma separated data.

String data = "id, name, organization \n" +
                    "1, Krishna, ABC Corporation \n" +
                    "2, Ram, XYZ Corporation \n" +
                    "3, Chamu, TUV Organization";

Step 2: Use ‘CDL.toJSONArray’ to get the JSONArray from given string data.

JSONArray jsonArray = CDL.toJSONArray(data);


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

App.java
package com.sample;

import org.json.CDL;
import org.json.JSONArray;

public class App {

 public static void main(String args[]) {
  String data = "id, name, organization \n" +
      "1, Krishna, ABC Corporation \n" +
      "2, Ram, XYZ Corporation \n" +
      "3, Chamu, TUV Organization";
  
  JSONArray jsonArray = CDL.toJSONArray(data);
  
  System.out.println(jsonArray);

 }
}

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

As you see in the above example, I supplied both the headers and data in same string. You can even separate headers from data in below way.

String data = "1, Krishna, ABC Corporation \n" +
                    "2, Ram, XYZ Corporation \n" +
                    "3, Chamu, TUV Organization";

JSONArray jsonArray = new JSONArray();
jsonArray.put("id");
jsonArray.put("name");
jsonArray.put("organization");

jsonArray =  CDL.toJSONArray(jsonArray, data);


App.java
package com.sample;

import org.json.CDL;
import org.json.JSONArray;

public class App {

 public static void main(String args[]) {
  String data = "1, Krishna, ABC Corporation \n" +
      "2, Ram, XYZ Corporation \n" +
      "3, Chamu, TUV Organization";
  
  JSONArray jsonArray = new JSONArray();
  jsonArray.put("id");
  jsonArray.put("name");
  jsonArray.put("organization");
  
  jsonArray =  CDL.toJSONArray(jsonArray, data);
   
  System.out.println(jsonArray);

 }
}



Previous                                                 Next                                                 Home

No comments:

Post a Comment