Convert java Object to CSV

后端 未结 4 1473
生来不讨喜
生来不讨喜 2021-02-20 11:46

What API should I use to convert Java object to CSV. Can I use google-gson for java object conversion to CSV format?

相关标签:
4条回答
  • 2021-02-20 12:32

    This is really more of an addition to the above post about using Jackson CSV. One issue I ran into is that it would raise any error on any properties in the object that were not in the CSV schema when I was doing it programatically and not using any annotations. Here is some example code that may be helpful. If you want to know more about why the filter and annotation introspector is necessary see here.

    public class CsvWriter {
    
    private final static String CSV_FILTER_NAME = "csvFilter";
    
    public void writeObjects( OutputStream outputStream,
                              List<?> objects,
                              CsvSchema csvSchema ) throws IOException
    {
        HashSet<String> columnNames = new HashSet<String>();
        for (CsvSchema.Column column : csvSchema) {
            columnNames.add( column.getName() );
        }
    
        SimpleBeanPropertyFilter csvReponseFilter =
                new SimpleBeanPropertyFilter.FilterExceptFilter(columnNames);
        FilterProvider filterProvider = new SimpleFilterProvider().addFilter( CSV_FILTER_NAME, csvReponseFilter );
    
        CsvMapper csvMapper = new CsvMapper();
        csvMapper.setFilters( filterProvider );
        csvMapper.setAnnotationIntrospector( new CsvAnnotationIntrospector() );
    
        ObjectWriter objectWriter = csvMapper.writer(csvSchema);
        objectWriter.writeValue( outputStream, objects);
    }
    
    private class CsvAnnotationIntrospector extends JacksonAnnotationIntrospector {
        @Override
        public Object findFilterId(Annotated a) {
            return CSV_FILTER_NAME;
        }
    }
    
    }
    

    and here is an example of how it can be used:

    public class CsvWriterTest extends TestCase {
    
    public void testWriteObjects() throws Exception {
        Vector <Entity> entities = new Vector<Entity>();
        entities.add( new Entity("Test entity 1", "Test description 1", "Test unused field"));
        entities.add(new Entity("Test entity 2", "Test description 2", "Test unused field"));
    
        CsvSchema csvSchema = CsvSchema.builder()
                .addColumn("name")
                .addColumn("description")
                .setUseHeader( true )
                .build()
                .withLineSeparator("\r\n");
    
        CsvWriter csvWriter = new CsvWriter();
        csvWriter.writeObjects(System.out, entities, csvSchema);
    }
    
    public class Entity {
        private String name;
        private String description;
        private String unusedField;
        // constructor, getter and setter methods omitted for brevity
    }
    
    }
    

    Output from the test method is:
    name,description
    "Test entity 1","Test description 1"
    "Test entity 2","Test description 2"

    0 讨论(0)
  • 2021-02-20 12:38

    The library json2flat can convert JSON documents to CSV format.

    It doesn't depends upon any POJO's to get you CSV.

    After all it's the user's perspective that how they want to view their JSON documents in CSV representation.

    0 讨论(0)
  • 2021-02-20 12:42

    Jackson provides for easy conversion to/from CSV (with Java and/or JSON).

    The post at http://www.cowtowncoder.com/blog/archives/2012/03/entry_468.html describes well how to use it.

    0 讨论(0)
  • 2021-02-20 12:51

    please give me your specific requirements about GSON.

    Gson provides toJson() and fromJson() methods to convert Java objects to JSON and vice-versa.

    can u refer this link. This link gives the list of API available under the GSON

    0 讨论(0)
提交回复
热议问题