csv轉JSON再轉Object List的方法

第一步,從.csv文件讀取數據,轉成JSON格式
 1 import com.fasterxml.jackson.dataformat.csv.CsvMapper;  2 import com.fasterxml.jackson.dataformat.csv.CsvSchema;  3 import com.google.gson.Gson;  4  
 5 public static String readFile(String filename) throws Exception {  6 
 7         String filetype = filename.substring(filename.lastIndexOf(".") + 1);  8         String filepath = "src/main/java/"+ filename;  9         String json = null; 10 
11         if (filetype.equals("csv")) { 12             
13             File input = new File(filepath); 14             CsvSchema csvSchema = CsvSchema.builder().setUseHeader(true).build(); 15             CsvMapper csvMapper = new CsvMapper(); 16 
17             // Read data from CSV file
18             List<Object> readAll = csvMapper.readerFor(Map.class) 19       .with(csvSchema).readValues(input).readAll(); 20             Gson objJson = new Gson(); 21             json = objJson.toJson(readAll, List.class); 22  } 23         return json; 24     }
 
第二步,建立Object類
 1 import com.fasterxml.jackson.annotation.JsonProperty;  2 
 3 public class User {  4     
 5     @JsonProperty("Userid")  6     private String Userid;  7     
 8     @JsonProperty("FirstName")  9     private String FirstName; 10     
11     @JsonProperty("LastName") 12     private String LastName; 13   
14    public String getUserId() { 15         return Userid; 16  } 17     
18     public String getFirstName() { 19         return FirstName; 20  } 21     
22     public String getLastName() { 23         return LastName; 24  } 25    
26     public void setUserId(String Userid) { 27         this.Userid = Userid; 28  } 29     
30     public void setFirstName(String FirstName) { 31         this.FirstName = FirstName; 32  } 33 
34     public void setLastName(String LastName) { 35         this.LastName = LastName; 36  } 37 }
 
第三步,將JSON字符串轉化爲Object List
 1 import com.fasterxml.jackson.databind.ObjectMapper;  2  
 3 public static List<User> jsonToUserEntity(String json) {  4         ObjectMapper objectMapper = new ObjectMapper();  5 
 6         try {  7            return objectMapper.readValue(  8  json,  9            objectMapper.getTypeFactory().constructCollectionType(List.class, User.class) 10  ); 11 
12         } catch (IOException e) { 13  e.printStackTrace(); 14  } 15         return new ArrayList<User>(); 16     }

 

補充:
若是CSV文件的第一行是Column名,而你想要自定義它們,能夠用下面的方法
1 CsvSchema csvSchema = CsvSchema.builder().setSkipFirstDataRow(true) 2                     .addColumn("userId") 3                     .addColumn("firstName") 4                     .build()
 
若是CSV文件自己沒有分列,只是按行存放了數據內容(第一行仍是Column名),則能夠用下面的方法
 1 CsvSchema schema = CsvSchema.builder().setColumnSeparator(',').setSkipFirstDataRow(true).build();  2  MappingIterator<String[]> it = csvMapper.readerFor(String[].class).with(schema).readValues(input);  3  
 4 List<String> recordList = new ArrayList<String>();  5  
 6 while (it.hasNext()) {  7                 String[] arr = it.next();  8                 String record = "";  9                 for (int i=0; i<arr.length; i++) { 10                    //arr[i]存放了一個單元格的內容,把一行中全部的單元格連起來就是一個完整的record
11                     if (arr[i] != "") { 12                         record = record + arr[i]; 13  } 14  } 15  recordList.add(record); 16             }
 
相關文章
相關標籤/搜索