简体   繁体   中英

Parse a csv String and map to a java object

I am trying to parse a csv string like this

    COL1,COL2,COL3
    1,2,3
    2,4,5

and map columns to a java object-

    Class Person{
       COL1,
       COL2,
       COL3;
     }

Most of the libraries I found on google are for csv files but I am working with google app engine so can't write or read files. currently I am using split method but problems with this approach is

  1. column that I am getting in csv string could vary as

     COL1,COL3,COL2 
  2. don't want to use boiler plate code of splitting and getting each column.so what I need is list of column header and read all columns in a collection using header mapper. While iterating, map column value to a java object.

There are several question based on similar type of requirement but none of them helped me. If anyone has done this before please could you share the idea? Thanks!

After searching and trying several libraries, I am able to solve it. I am sharing the code if anyone needs it later-

    public class CSVParsing {

      public void parseCSV() throws IOException {

      List<Person> list = Lists.newArrayList();

      String str = "COL1,COL2,COL3\n" +
                   "A,B,23\n" +
                   "S,H,20\n";

      CsvSchema schema = CsvSchema.emptySchema().withHeader();

      ObjectReader mapper = new CsvMapper().reader(Person.class).with(schema);

      MappingIterator<Person> it = mapper.readValues(str);
      while (it.hasNext()) {
          list.add(it.next());
      }

      System.out.println("stored list is:" + (list != null ? list.toString() : null));
  }}

Use a Tokenizer to split the string into objects then set them to the object.

 //Split the string into tokens using a comma as the token seperator
 StringTokenizer st = new StringTokenizer(lineFromFile, ",");

 while (st.hasMoreTokens()) 
 {
     //Collect each item  
     st.nextElement();
 } 

 //Set to object
 Person p = new Person(item1, item2, item3);

If the columns can be reversed, you parse the header line, save it's values and and use it to decide which column each token falls under using, say, a Map

String columns[] = new String[3]; //Fill these with column names

Map<String,String> map = new HashMap<>();
int i=0;

while (st.hasMoreTokens()) 
{
    //Collect each item  
    map.put(columns[i++], st.nextElement());
}

Then just, create the Person

 Person p = new Person(map.get("COL1"), map.get("COL2"), map.get("COL3"));

Most of the libraries I found on google are for csv files but I am working with google app engine so can't write or read files

You can read file (in project file system). You can read and write file in blobstore, google cloud storage

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM