-2

So I received a text file to create an API, and in this text file I have an example similar to this:

id,first_name,last_name
1,John,Smith
2,Charlie,Sheen

The list goes on with about 100+ rows. Is there a way to organize this programmatically?

I don't want to manually write this into json format. I'll take java, C#, Javascript, or php methods.

aschipfl
  • 33,626
  • 12
  • 54
  • 99

3 Answers3

1
public String[] returnArray(String line){
return line.split(",");}

This organizes the new array into the elements between each comma. In this example the first element would equal id.

user1231232141214124
  • 1,339
  • 3
  • 16
  • 22
0

There are lots of open source CSV readers out there for Java and other languages and I highly recommend using one of them. However, if you want a quickly working solution with no additional libraries you can use the following code. Make sure to edit the file name to point to wherever your text file is. Or you can edit the code to allow someone to pass the file name in. When you run this it will echo out the contents of the file.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ReadFile
{
    private static class Record
    {
        public String id;
        public String firstName;
        public String lastName;

        @Override
        public String toString()
        {
            return id + "," + firstName + "," + lastName;
        }
    }

    public static void main(String[] args) throws IOException
    {
        List<Record> records = getRecordsFromFile("C:/Myfile.txt");
        for(Record record : records)
        {
            System.out.println(record);
        }
    }

    private static List<Record> getRecordsFromFile(String fileName) throws IOException
    {
        List<Record> records = new ArrayList<>();
        BufferedReader reader = null;
        try
        {
            reader = new BufferedReader(new FileReader(new File(fileName)));
            String line = null;
            while((line = reader.readLine()) != null)
            {
                records.add(makeRecordFromLine(line));
            }
            return records;
        }
        finally
        {
            if(reader != null)
            {
                reader.close();
            }
        }
    }

    private static Record makeRecordFromLine(String line)
    {
        String[] lineArray = line.split(",");
        Record record = new Record();
        record.id = lineArray[0];
        record.firstName = lineArray[1];
        record.lastName = lineArray[2];
        return record;
    }
}
Josh Chappelle
  • 1,558
  • 2
  • 15
  • 37
0

you can use past special techniques to read all the json please have a look into this link: How to show the "paste Json class" in visual studio 2012 when clicking on Paste Special?

Community
  • 1
  • 1