我正在尝试将Object编组为csv String。我创建了一种可以将任何对象转换为csv String的方法,但是我不断收到异常:

java.lang.NoSuchMethodError: org.codehaus.jackson.map.ObjectMapper.writer(Lorg/codehaus/jackson/FormatSchema;)Lorg/codehaus/jackson/map/ObjectWriter;


元帅法:

public static final synchronized String marshal(final Object object, final CsvSchema csvSchema) throws IOException {
        String CSV_FILTER_NAME = "csvFilter";
        HashSet<String> columnNames = new HashSet<>();
        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 JacksonAnnotationIntrospector() {
            @Override
            public Object findFilterId(AnnotatedClass annotatedClass) {
                return CSV_FILTER_NAME;
            }
        });
        ObjectWriter objectWriter = csvMapper.writer(csvSchema);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        objectWriter.writeValue(byteArrayOutputStream, csvSchema);
        return new String(byteArrayOutputStream.toByteArray(), "UTF-8");
    }


主要方法:

public static void main(String args[]) {
        CsvSchema csvSchema = CsvSchema.builder()
                .addColumn("name")
                .addColumn("age")
                .addColumn("height")
                .addColumn("weight")
                .setUseHeader(true)
                .build()
                .withLineSeparator("\n");
        Person person = new Person("Tim", "32", "184", "100");
        try {
            System.out.println(CsvUtilities.marshal(person, csvSchema));
        } catch (IOException ex) {
            Logger.getLogger(CsvUtilities.class.getName()).log(Level.SEVERE, null, ex);
        }
    }


是什么导致此异常?

编辑这是我所有的进口:

import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.List;
import java.util.logging.Logger;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.map.ObjectWriter;
import org.codehaus.jackson.map.introspect.AnnotatedClass;
import org.codehaus.jackson.map.introspect.JacksonAnnotationIntrospector;
import org.codehaus.jackson.map.ser.FilterProvider;
import org.codehaus.jackson.map.ser.impl.SimpleBeanPropertyFilter;
import org.codehaus.jackson.map.ser.impl.SimpleFilterProvider;

最佳答案

在课程路径中查看罐子。可能有两种或不同版本的杰克逊罐子没有此方法。可能是Class loader加载了较旧的版本。

还检查您已添加到项目中的依赖项。

09-05 11:12