SoFunction
Updated on 2025-03-08

Java implements CSV format to object

introduce

The full name of csv is "Comma-Separated Values", which is a file in comma-separated value format and a plain text format file used to store data. A CSV file consists of any number of records, separated by some newline character; each record consists of fields, and the delimiter between fields is other characters or strings.

I found that there are basically no shortcut conversion methods and toolkits on Baidu. Basically, the ones that can be found cannot be written in general. There is no way to write them out by yourself. The main technologies used are reflection, generics, type conversion, and constructor design patterns. The following code provides an idea. If the technology is similar, I basically read the following code that can be written by myself. If you are an entry-level Java programmer, you can skip this blog by yourself.

Reference code

Some tool class codes are not displayed, so I paste the main core principles here, it is very simple and I can write them myself.

package ;

import ;
import ;
import ;
import ;
import ;

import ;
import ;
import ;
import ;
import ;

/**
  * csv to object
  * @Author: huanmin
  * @Date: 2022/6/18 15:59
  * @Version: 1.0
  * @Description: Detailed description of the function of the file...
  */
public class CSVToObj<T> extends ParameterizedTypeReference<T> {
    private String separator  ;  //Default delimiter    private List<String> objects ;//data    private List<T> list=new ArrayList<>();//data    private Map<String,String> fieldsTypes = new LinkedHashMap<>();
    public CSVToObj(List<String> objects,String separator) {
        //Treatment of special symbols         = (separator);
        =objects;
    }
    // When converting columns, mappings, and mappings, the order of mappings will be consistent. By default, the delimiter of the current file is used as the cutting.    public CSVToObj<T>  mapping(String fieldNames){
        String[] split = (separator);
        Class<? extends CSVToObj> aClass = (getClass(),0);
        Field[] declaredFields = ();
        for (String s : split) {
            for (Field declaredField : declaredFields) {
                (true);
                if((())){
                    ((), ().getTypeName());
                }
            }
        }
        return this;
    }

    @SneakyThrows
    public CSVToObj<T>  transform(){
        Class<? extends CSVToObj> aClass = (getClass(),0);
        for (String object : objects) {
            String[] split = (separator);
            T o = (T)();
            Field[] declaredFields = ().getDeclaredFields();
            for (int i = 0; i < ; i++) {
                Field declaredField = declaredFields[i];
                (true);
                if ((())) {
                    (o, (split[i],(())));
                }
            }
            (o);
        }
        return this;
    }
    public List<T>  result(){
        return list;
    }


}

Test cases

package ;

import ;
import ;
import ;
import ;
import ;

import ;
import ;

/**
  * csv to object testing
  *
  * @Author: huanmin
  * @Date: 2022/6/18 16:44
  * @Version: 1.0
  * @Description: Detailed description of the function of the file...
  */
public class CSVToObjTest {

    @Test
    public void show1(){
        File absoluteFileOrDirPathAndCreateNewFile = ("/file/");
        //Read the corresponding fields of the head        String head = (absoluteFileOrDirPathAndCreateNewFile);
        //Remove unnecessary information from the head and tail, and only display content        List<String> list = (absoluteFileOrDirPathAndCreateNewFile);
        //Make the mapping and then convert the csv format to an entity object        List<UserData> result = new CSVToObj<UserData>(list, "|"){}.mapping(head).transform().result();
        for (UserData userData : result) {
            (userData);
        }
    }
    @Test
    public void show2(){
        File absoluteFileOrDirPathAndCreateNewFile = ("/file/");
        //Manually specify the file header        String head ="id|name|pass|age|sex|site";
        //Remove unnecessary information from the head and tail, and only display content        List<String> list = (absoluteFileOrDirPathAndCreateNewFile);
        List<UserData> result = new CSVToObj<UserData>(list, "|"){}.mapping(head).transform().result();
        for (UserData userData : result) {
            (userData);
        }
    }

    //
}

The above is the detailed content of Java implementing CSV format to object. For more information about Java CSV conversion to object, please pay attention to my other related articles!