Search code examples
javacsvserializationjacksonjackson-modules

JsonGenerationException: CSV generator does not support Object values for properties


I'm trying to serialize Foo into a String. It seems like a pretty simple task but for some reason DateTime seems to break it.

Test.java

import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.joda.time.DateTime;

public class Test {

    public static void main(String args[]) {
        try {
            List<Foo> foos = new ArrayList<>();
            Foo foo = new Foo();
            foo.setID(1);
            foo.setCURRENT(new DateTime(new Timestamp(System.currentTimeMillis())));
            foos.add(foo);
            String content = serialize(foos, Foo.class, Boolean.TRUE);
            System.out.println(content);
        } catch (IOException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static final synchronized String serialize(final Object object, final Class type, final Boolean withHeaders) throws IOException {
        CsvMapper csvMapper = new CsvMapper();
        CsvSchema csvSchema;
        if (withHeaders) {
            csvSchema = csvMapper.schemaFor(type).withHeader();
        } else {
            csvSchema = csvMapper.schemaFor(type).withoutHeader();
        }
        return csvMapper.writer(csvSchema).writeValueAsString(object);
    }

}

Foo.java

import org.joda.time.DateTime;

public class Foo {

    private Integer ID;
    private DateTime CURRENT;

    public Foo() {
    }

    public Integer getID() {
        return ID;
    }

    public void setID(Integer ID) {
        this.ID = ID;
    }

    public DateTime getCURRENT() {
        return CURRENT;
    }

    public void setCURRENT(DateTime CURRENT) {
        this.CURRENT = CURRENT;
    }

}

I've tried using @JsonGetter and @JsonSetter in my Foo object but it doesn't really make any impact.

What is causing this error?


Solution

  • Are you including datatype module for Joda DateTime? The one you need is jackson-datatype-joda, from https://github.com/FasterXML/jackson-datatype-joda. If not, that would explain the issue, since values would be seen as regular POJOs, and CSV is not good for nested data without some sort of mapping to dotted notation.