How do I serialize & deserialize CSV properly?

Hooli

I've been trying to serialize an object to a CSV String but the object contains a List and @JsonUnwrapped doesn't work on List objects.

Expected sample output:

color,part.name\n
red,gearbox\n
red,door\n
red,bumper

Actual output:

com.fasterxml.jackson.core.JsonGenerationException: Unrecognized column 'name':

Here is my code: (Most of it is the 2 POJO's)

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.annotation.JsonRootName;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import java.io.IOException;
import static java.util.Arrays.asList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

public class NestedWrapping {

@JsonRootName("Car")
@JsonInclude(JsonInclude.Include.NON_DEFAULT)
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, setterVisibility = JsonAutoDetect.Visibility.NONE)
@JsonPropertyOrder({"color"})
public static class Car {

    @JsonProperty("color")
    private String color;

    @JsonFormat(shape = JsonFormat.Shape.STRING)
    @JacksonXmlElementWrapper(useWrapping = false)
    private List<Part> parts;

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public List<Part> getParts() {
        return parts;
    }

    public void setParts(List<Part> parts) {
        this.parts = parts;
    }

}

@JsonInclude(JsonInclude.Include.NON_DEFAULT)
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, setterVisibility = JsonAutoDetect.Visibility.NONE)
@JsonPropertyOrder({
    "name"
})
public static class Part {

    @JsonProperty("name")
    private String name;

    public String getName() {
        return name;
    }

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

}

public static void main(String args[]) {
    try {
        Car car = new Car();
        car.setColor("red");
        Part part1 = new Part();
        part1.setName("geabox");
        Part part2 = new Part();
        part2.setName("door");
        Part part3 = new Part();
        part3.setName("bumper");
        car.setParts(asList(part1, part2, part3));
        System.out.println("serialized: " + serialize(car, Car.class, true));
    } catch (IOException ex) {
        Logger.getLogger(NestedWrapping.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);
}

}

Nothing I try seems to work, I've read every post on stackoverflow and github about the topic but I can't find a working solution.

Sorry about any pointless annotations that I've left behind for no reason and if you answer with code, please feel free to remove them.

OneCricketeer

From the error, I would like to believe that it has something to do with your schema for a Car, which has the columns of {"color"} taken from @JsonPropertyOrder on Car and not a "name" value.

You probably want to add "parts" in there, but you would get the same error that "name" is not part of that schema.

After a few changes to your code, I was able to serialize and deserialize a Car object.

Part

Here, after some other changes it needed a constructor with a single String value, so add that

@JsonPropertyOrder({"name"})
public static class Part {
    @JsonProperty("name")
    private String name;

    public Part() {
        this("");
    }

    public Part(String partJSON) {
        // TODO: Unserialize the parameter... it is a serialized Part string... 
        this.name = partJSON;
    }

Car

Here, you will need to implement a method that will convert the List<Part> into a CSV-readable format manually.

Such a method would look like this

@JsonGetter("parts")
public String getPartString() {
    String separator = ";";
    StringBuilder sb = new StringBuilder();

    Iterator<Part> iter = this.parts.iterator();
    while (iter.hasNext()) {
        Part p = iter.next();
        sb.append(p.getName());

        if (iter.hasNext())
            sb.append(separator);
    }

    return sb.toString();
} 

Also, don't forget to fix the schema at the top of the class

@JsonPropertyOrder({"color", "parts"})
public static class Car {

    @JsonProperty("color")
    private String color;
    @JsonProperty("parts")
    private List<Part> parts;

    public Car() {
        this.parts = new ArrayList<>();
    }

serialize

You can change your serialize method to take the type of the class as a generic type parameter instead of an explicit Class like so.

public static final synchronized <T> String serialize(final T object, final Boolean withHeaders) throws IOException {
    CsvMapper csvMapper = new CsvMapper();
    CsvSchema csvSchema = csvMapper.schemaFor(object.getClass());

    if (withHeaders) {
        csvSchema = csvSchema.withHeader();
    } else {
        csvSchema = csvSchema.withoutHeader();
    }

    return csvMapper.writer(csvSchema).writeValueAsString(object);
}

main - writer

Now, if you serialize a Car, you should see

color,parts
red,gearbox;door;bumper

main - reader

And reading that CSV string and looping over the Car.getParts()

Car car = mapper.readerFor(Car.class).with(csvSchema).readValue(csv);

for (Part p : car.getParts()) {
    System.out.println(p.getName());
}
gearbox
door
bumper

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

How do I serialize & deserialize CSV properly?

From Dev

How do I, using XStream, serialize/deserialize objects in a type hierarchy?

From Dev

How do I correctly serialize/deserialize a complex Swift object to as an AWS Lambda payload?

From Dev

Do I have to serialize/deserialize the object in silverlight application with WCF?

From Dev

How can I use Kryo to serialize an object and deserialize it again?

From Dev

how to serialize/deserialize a map in go

From Dev

Julia: how stable are serialize() / deserialize()

From Dev

How to serialize/deserialize list with interface

From Dev

How do I serialize this kind of json?

From Dev

How do I serialize a LabeledPoint RDD in PySpark?

From Dev

How do I serialize a variable in VimScript?

From Dev

How do I serialize or save to a file a Thunk?

From Dev

How do I serialize a complex Class in GWT?

From Dev

How do i serialize an empty jsonapi object

From Dev

How do I deserialize json into PropertyType?

From Dev

How do I deserialize Json with modifying the structure?

From Dev

How do I deserialize timestamps that are in seconds with Jackson?

From Dev

How do I Deserialize Just a String with Namespace?

From Dev

How do I deserialize a kafka message to a POJO?

From Dev

How do I deserialize a Player's inventory?

From Dev

How do I deserialize a Json object?

From Dev

Can I serialize/deserialize System Types to XML?

From Dev

How can I serialize/deserialize a dictionary with custom keys using Json.Net?

From Dev

How can i deserialize and serialize complex json data bu Newton json?

From Dev

How to serialize/deserialize using illinois-edison

From Dev

How to Deserialize and Serialize Build Process Parameters in TFS

From Dev

How to serialize/deserialize Ecto model with Loaded associations?

From Dev

How to completely serialize/deserialize RSAParameters object

From Dev

How to serialize/deserialize "splashed" complex type?

Related Related

  1. 1

    How do I serialize & deserialize CSV properly?

  2. 2

    How do I, using XStream, serialize/deserialize objects in a type hierarchy?

  3. 3

    How do I correctly serialize/deserialize a complex Swift object to as an AWS Lambda payload?

  4. 4

    Do I have to serialize/deserialize the object in silverlight application with WCF?

  5. 5

    How can I use Kryo to serialize an object and deserialize it again?

  6. 6

    how to serialize/deserialize a map in go

  7. 7

    Julia: how stable are serialize() / deserialize()

  8. 8

    How to serialize/deserialize list with interface

  9. 9

    How do I serialize this kind of json?

  10. 10

    How do I serialize a LabeledPoint RDD in PySpark?

  11. 11

    How do I serialize a variable in VimScript?

  12. 12

    How do I serialize or save to a file a Thunk?

  13. 13

    How do I serialize a complex Class in GWT?

  14. 14

    How do i serialize an empty jsonapi object

  15. 15

    How do I deserialize json into PropertyType?

  16. 16

    How do I deserialize Json with modifying the structure?

  17. 17

    How do I deserialize timestamps that are in seconds with Jackson?

  18. 18

    How do I Deserialize Just a String with Namespace?

  19. 19

    How do I deserialize a kafka message to a POJO?

  20. 20

    How do I deserialize a Player's inventory?

  21. 21

    How do I deserialize a Json object?

  22. 22

    Can I serialize/deserialize System Types to XML?

  23. 23

    How can I serialize/deserialize a dictionary with custom keys using Json.Net?

  24. 24

    How can i deserialize and serialize complex json data bu Newton json?

  25. 25

    How to serialize/deserialize using illinois-edison

  26. 26

    How to Deserialize and Serialize Build Process Parameters in TFS

  27. 27

    How to serialize/deserialize Ecto model with Loaded associations?

  28. 28

    How to completely serialize/deserialize RSAParameters object

  29. 29

    How to serialize/deserialize "splashed" complex type?

HotTag

Archive