10

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

Programmer Bruce
  • 64,977
  • 7
  • 99
  • 97

4 Answers4

6

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.

Programmer Bruce
  • 64,977
  • 7
  • 99
  • 97
2

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.

skap
  • 493
  • 4
  • 9
1

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

user1355253
  • 95
  • 1
  • 1
  • 8
  • 1
    This talks about converting JSON to a Java object, but I would like to know if it would be possible to convert CSV to Java using gson –  Aug 03 '12 at 10:33
  • I think we cant directly convert CSV to Java using Gson.The way is convert Gson to json and then only convert to java object. can u refer this link for How to convert Java object to / from JSON (Gson) http://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/ – user1355253 Aug 03 '12 at 11:32
1

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"

Community
  • 1
  • 1
Rob Baily
  • 2,770
  • 17
  • 26