我一直在尝试将对象序列化为 CSV String
,但该对象包含 aList
并且@JsonUnwrapped
不适用于List
对象。
预期样本输出:
color,part.name\n
red,gearbox\n
red,door\n
red,bumper
实际输出:
com.fasterxml.jackson.core.JsonGenerationException: Unrecognized column 'name':
这是我的代码:(大部分是 2 个 POJO)
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);
}
}
我尝试的任何方法似乎都不起作用,我已经阅读了有关该主题的 stackoverflow 和 github 上的每篇文章,但我找不到有效的解决方案。
抱歉,我无缘无故留下了任何毫无意义的注释,如果您用代码回答,请随时删除它们。