Home > Software engineering >  Extract items from JSONArray containing ArrayList stored from TSV and assign it to String one by one
Extract items from JSONArray containing ArrayList stored from TSV and assign it to String one by one

Time:01-04

I have a JSONArray named DataExtract containing objects like below extracted from a TSV file: enter image description here

The requirement is to extract the items one by one like extract the value from records1's 0th element : agent_4 and assign to a String named ID, then records1's 1st element and assign it to text and same for records[2]'s 2nd element. And the final output should look like below :

DataExtract = { ID : agent_4, text = "Can i text you the information" count = 1 ,

ID: agent_11, text = "", count =2,

} How can i achieve this ? or there is some other way to store the arraylist information and assign it one by one

Current code which is getting me as one single jsonArray :

List<List<String>> records = new ArrayList<>();
        try (BufferedReader br = new BufferedReader(new FileReader(content))) {
            String line;
            //todo to check if it is required to be sent via Map or Json Object
            
            while ((line = br.readLine()) != null) {
                String[] values = line.split("\t");
                records.add(Arrays.asList(values));
            }
            Gson gson = new Gson();
            String jsonArray = gson.toJson(records);
            logger.debug("Print value{}", jsonArray);
            JSONObject obj = new JSONObject();
            obj.put("Data:", jsonArray);
            for(int i =0;i<jsonArray.size();i  ) { //for jsonArray
              for(int j=0;j<i;j  ) { //inner loop for each elements
               
               String candidateID=String.valueOf(jsonArray.get(j));
                    }  //but it is getting the entire string not separate elements like i want to extract agent_4 only in this string , the split is also not working

CodePudding user response:

Worked with JSONObject:

Load file by BufferedReader and use JsonArray to format your Json output

BufferedReader reader = new BufferedReader(new FileReader("data.tsv"));

String[] fieldNames = reader.readLine().split("\t");


List<JSONObject> rows = new ArrayList<>();

// Read tsv file line by line
String line;
while ((line = reader.readLine()) != null) {
    
    String[] fields = line.split("\t");

    JSONObject row = new JSONObject();
    for (int i = 0; i < fieldNames.length; i  ) {
        row.put(fieldNames[i], fields[i]);
    }
    rows.add(row);
}

reader.close();

// Convert the list of rows to a JSON array
JSONArray array = new JSONArray(rows);
  • Related