3

I am having free text available into the file. I am stucked while convert it into the json string array

The columns names are variable and can be n number of columns

email_from,email_to,DATE_CHANGED

samwilliams@gmail.com, mike_haley@gmail.com, 1447666867

smithpaul@gmail.com, angierussell@gmail.com, 1447668867

The first line is of headers, and the rest of all the lines are their values. So, every line would contain, same number of parameters with respect to each column. Columns are comma separated.

The json string response should be looked like this

{
 "data": [
    {
        "email_from": "samwilliams@gmail.com",
        "email_to": "mike_haley@gmail.com",
        "DATE_CHANGED": "1447666867"
    },
    {
        "email_from": "smithpaul@gmail.com",
        "email_to": "angierussell@gmail.com",
        "DATE_CHANGED": "1447668867"
    }
 ]
}
Andreas
  • 154,647
  • 11
  • 152
  • 247
Angie Russell
  • 87
  • 2
  • 9

3 Answers3

2

The following code opens a file with comma-delimited strings and uses while loop to construct JsonObject and then keeps adding them to the JsonArray and finally prints it (Please add your validations as well you could move majority of the code out of try block if you wish to make the code perform better).

It addresses the need for having n number of columns in the file.

package gjson;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

public class GJSONTest {
    public static void main(String[] args) {

        // create an array called datasets
        JsonArray datasets = new JsonArray();

        File file = new File("C:\\test_stackoverflow\\list.txt");

        try (BufferedReader br = new BufferedReader(new FileReader(file)))  {
            String line;
            boolean flag = true; 
            List<String> columns = null; 
            while ((line = br.readLine()) != null) {
               if (flag) {
                   flag = false; 
                   //process header 
                   columns = Arrays.asList(line.split(","));
               } else {
                   //to store the object temporarily
                   JsonObject obj = new JsonObject(); 
                   List<String> chunks = Arrays.asList(line.split(","));

                   for(int i = 0; i < columns.size(); i++) {
                       obj.addProperty(columns.get(i), chunks.get(i));
                   }
                   datasets.add(obj); 
               } 
            }
        } catch(FileNotFoundException fnfe) {
            System.out.println("File not found.");
        } catch(IOException io) {
            System.out.println("Cannot read file.");
        }

        Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create();
        System.out.println(gson.toJson(datasets));
    }
}

See the following screenshots (below with 3 columns)

enter image description here

Added another column to the text file and following is the output.

enter image description here

Here is the sample .txt file containing your data

enter image description here

Raf
  • 7,505
  • 1
  • 42
  • 59
2
private String getParsedData(String data){

    String[] lines = data.split("\\r?\\n");

    List<Map> dataList = new ArrayList<Map>();


    int colCount = 0;

    if(lines.length > 1){

        String keyLine = lines[0];

        String[] keys = keyLine.split(",");

        for(int i = 1; i < lines.length; i++){

            colCount = 0;
            Map<String, Object> rawObj = new HashMap<String, Object>();

            try {

                String[] values = lines[i].split(",");

                for(String value: values){

                    rawObj.put(keys[colCount], value);
                    colCount++;
                }   

            } catch (Exception e) {

            }

            dataList.add(rawObj);
        }
    }


    Map<String, Object> rawObj = new HashMap<String, Object>();
    rawObj.put("data", dataList);
    Gson gson = new Gson();

    String res = gson.toJson(rawObj);

    return res;
}

String data = "email_from,email_to,DATE_CHANGED\r\nsamwilliams@gmail.com, mike_haley@gmail.com, 1447666867\r\nsmithpaul@gmail.com, angierussell@gmail.com, 1447668867";

But I am not sure whether its an efficient code or not.

Angie Russell
  • 87
  • 2
  • 9
  • The reason I have used try/catch block in my answer is because I assumed you are reading the data from a file but, I don't see the need for try/catch block in this answer so you can remove that. I decided to use generics (list and hashmap) but, then I noticed that I could achieve the task without their usage hence my answer. If not mistaken there should be a difference in performance when a task is achieved with/without use of list and hashmap but, the performance difference might be so little to observe or make an impact. – Raf Nov 16 '15 at 11:43
1

Try this code:

public class ContactObject {
    private String emailFrom;
    private String emailTo;
    private String dateChanged;

    public ContactObject(String emailFrom, String emailTo, String dateChanged) {
        this.emailFrom = emailFrom;
        this.emailTo = emailTo;
        this.dateChanged = dateChanged;
    }

    @Override
    public String toString() {
        return "{email_from:" + emailFrom + ", email_to:" + emailTo + ", DATE_CHANGED:" + dateChanged;
    }
}

public class ContactJSON {
    private List<ContactObject> data;

    public ContactJSON(List<ContactObject> contactList) {
        this.data = contactList;
    }
}

Then in your main() method you can make use of these classes:

public static void main(String[] args) {
    List<ContactObject> contactList = new ArrayList<ContactObject>();
    ContactObject obj1 = new ContactObject("samwilliams@gmail.com", "mike_haley@gmail.com", "1447666867");
    ContactObject obj2 = new ContactObject("smithpaul@gmail.com", "angierussell@gmail.com", "1447668867");
    contactList.add(obj1);
    contactList.add(obj2);

    Gson gson = new Gson();
    String json = gson.toJson(new ContactJSON(contactList));
    System.out.println(json);
}

Output:

{"data":[{"emailFrom":"samwilliams@gmail.com","emailTo":"mike_haley@gmail.com","dateChanged":"1447666867"},{"emailFrom":"smithpaul@gmail.com","emailTo":"angierussell@gmail.com","dateChanged":"1447668867"}]}
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • Hi Tim, Thanks for the code, it would work, but the issue is that the column names are not fixed. It can be vary and can be n numbers. So I am stucked to create the dynamic script whose column names can be handled at the run time. – Angie Russell Nov 16 '15 at 10:31
  • I'm not entirely sure what you mean. Can you update your question to reflect this? – Tim Biegeleisen Nov 16 '15 at 10:35
  • In above question, I have mentioned "The columns names are variable and can be n number of columns".. It means, you can have any column names, so we cannot create the POJO class for Serialization into json. – Angie Russell Nov 16 '15 at 10:41
  • So the email_from,email_to,DATE_CHANGED column names can vary at the runtime, and we need to handle this into that way. – Angie Russell Nov 16 '15 at 10:42
  • Why not use a list for the arbitrary number of items? – Tim Biegeleisen Nov 16 '15 at 10:47