2

With Jackson, I need to convert an instance of my class Test in CSV but I'm getting problems with a class that contains one list (Inner)

Ex:

public class Test {

    String testName;

    @JsonUnwrapped
    Simple simple;

    @JsonUnwrapped
    Inner inner;

    public Test(String testName, Simple simple, Inner inner) {
        this.testName = testName;
        this.simple = simple;
        this.inner = inner;
    }

    public String getTestName() {
        return testName;
    }

    public void setTestName(String testName) {
        this.testName = testName;
    }

    public Simple getSimple() {
        return simple;
    }

    public void setSimple(Simple simple) {
        this.simple = simple;
    }

    public Inner getInner() {
        return inner;
    }

    public void setInner(Inner inner) {
        this.inner = inner;
    }
}

class Inner {
    @JsonUnwrapped
    List<Person> persons;

    public Inner(List<Person> persons) {
        this.persons = persons;
    }

    public List<Person> getPersons() {
        return persons;
    }

    public void setPersons(List<Person> persons) {
        this.persons = persons;
    }
}

class Person {
    String name;

    public Person(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

class Simple {
    String simpleName;

    public Simple(String simpleName) {
        this.simpleName = simpleName;
    }

    public String getSimpleName() {
        return simpleName;
    }

    public void setSimpleName(String simpleName) {
        this.simpleName = simpleName;
    }
}

class Main {
    public static void main(String[] args) {
        Simple simple = new Simple("simple");
        Person person = new Person("jesus");
        Inner inner = new Inner(Arrays.asList(person));

        Test test = new Test("test", simple, inner);
        CsvMapper mapper = new CsvMapper();
        CsvSchema schema = mapper.schemaFor(Test.class);
        try {
            String csv = mapper.writer(schema).writeValueAsString(test);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

    }
}

For objects properties, I used the annotation @JsonUnwrapped as recommended on this link , but I get one exception when jackson try to convert the list Inner.persons:

enter image description here

How can I fix that ?

Jesus Zavarce
  • 1,729
  • 1
  • 17
  • 27
  • The docs (https://fasterxml.github.io/jackson-annotations/javadoc/2.0.0/com/fasterxml/jackson/annotation/JsonUnwrapped.html) says "can not unwrap JSON arrays using this mechanism" – Perdi Estaquel Nov 23 '18 at 00:40

0 Answers0