Jackson处理xml和csv和java对象互转
程序员文章站
2022-05-01 17:43:56
...
Jackson处理json,xml,csv
可以方便地实现序列化和反序列化,实现三者互转以及java bean互转
maven依赖
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.6.3</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.6.3</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.6.3</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-csv</artifactId> <version>2.7.3</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-xml</artifactId> <version>2.7.3</version> </dependency> <dependency> <groupId>org.codehaus.woodstox</groupId> <artifactId>woodstox-core-asl</artifactId> <version>4.4.1</version> </dependency>
Xml工具类
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.dataformat.xml.XmlMapper; public class XmlUtil { private static final Logger logger = LogManager.getLogger(XmlUtil.class); private static final XmlMapper xmlMapper = new XmlMapper(); private XmlUtil() { } /** * 输出全部属性 如果xml中存在,对象中没有,则自动忽略该属性 失败返回null * * @param xmlContent * @param clazz * @return */ public static <T> T toNormalObject(String xmlContent, Class<T> clazz) { return xmlToObject(xmlContent, clazz); } /** * 输出全部属性 * 如果xml中存在,对象中没有,则自动忽略该属性 * 失败返回null * @param inputStream * @param clazz * @return */ public static <T> T toNormalObject(byte[] bytes, Class<T> clazz) { return xmlToObject(bytes, clazz); } /** * 输出全部属性 失败返回"" * * @param object * @return */ public synchronized static byte[] toNormalXml(Object object) { return objectToXml(Include.ALWAYS, object); } private static <T> T xmlToObject(byte[] bytes, Class<T> clazz) { try { return xmlMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES).readValue(bytes, clazz); } catch (Exception e) { logger.info("XmlToObject failed:", e); } return null; } private static <T> T xmlToObject(String xmlContent, Class<T> clazz) { try { return xmlMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES).readValue(xmlContent, clazz); } catch (Exception e) { logger.info("XmlToObject failed:", e); } return null; } private static <T> byte[] objectToXml(Include include, T object) { try { return xmlMapper.setSerializationInclusion(include).writerWithDefaultPrettyPrinter().writeValueAsBytes(object); } catch (JsonProcessingException e) { logger.info("ObjToXml failed:", e); } return null; } }
Csv工具类
import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.MappingIterator; import com.fasterxml.jackson.dataformat.csv.CsvMapper; import com.fasterxml.jackson.dataformat.csv.CsvSchema; public class CsvUtil { private static final Logger logger = LogManager.getLogger(CsvUtil.class); private static final CsvMapper csvMapper = new CsvMapper(); private CsvUtil(){ } /** * 输出全部属性 * 如果csv中存在,对象中没有,则自动忽略该属性 * 失败返回null * * @param csvContent * @param clazz * @return */ public static <T> List<T> toNormalObject(String csvContent, Class<T> clazz) { try { CsvSchema schema = CsvSchema.emptySchema().withHeader(); MappingIterator<T> mappingIterator = csvMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES).readerFor(clazz).with(schema).readValues(csvContent); return mappingIterator.readAll(); } catch (Exception e) { logger.info("CsvToObject failed:", e); } return null; } /** * 输出全部属性 * 如果csv中存在,对象中没有,则自动忽略该属性 * 失败返回null * @param inputStream * @param clazz * @return */ public synchronized static <T> List<T> toNormalObject(byte[] bytes, Class<T> clazz) { try { CsvSchema schema = CsvSchema.emptySchema().withHeader(); MappingIterator<T> mappingIterator = csvMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES).readerFor(clazz).with(schema).readValues(bytes); return mappingIterator.readAll(); } catch (Exception e) { logger.info("CsvToObject failed:", e); } return null; } /** * 输出全部属性 失败返回"" * * @param object * @return */ public static String toNormalCsv(Object object) { return objectToCsv(Include.ALWAYS, object); } private static <T> String objectToCsv(Include include, T object) { try { CsvSchema csvSchema = csvMapper.schemaFor(object.getClass()); return csvMapper.setSerializationInclusion(include).writer(csvSchema).writeValueAsString(object); } catch (JsonProcessingException e) { logger.info("ObjToCsv failed:", e); } return ""; } }
Json工具类
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; public class JsonUtil { private static final Logger logger = LoggerFactory.getLogger(JsonUtil.class); private static ObjectMapper objectMapper = new ObjectMapper(); /** * 输出全部属性 * 失败返回"" * @param object * @return */ public static String toNormalJson(Object object) { return toJson(Include.ALWAYS, object); } /** * 输出非空属性 * 失败返回"" * @param object * @return */ public static String toNonNullJson(Object object) { return toJson(Include.NON_NULL, object); } /** * 输出非Null且非Empty(如List.isEmpty)的属性 * 失败返回"" * @param object * @return */ public static String toNonEmptyJson(Object object) { return toJson(Include.NON_EMPTY, object); } /** * 转成Json * @param include * @param object * @return */ private static String toJson(Include include, Object object) { try { objectMapper.setSerializationInclusion(include); return objectMapper.writeValueAsString(object); } catch (Exception e) { logger.info("Obj转Json报错:", e); } return ""; } /** * 输出全部属性 * 如果json中存在,对象中没有,则自动忽略该属性 * 失败返回null * * @param json * @param clazz * @return */ public static <T> T toNormalObject(String json, Class<T> clazz) { return toObject(json, clazz); } /** * 转成Object * @param include * @param json * @param clazz * @return */ private static <T> T toObject(String json, Class<T> clazz) { try { objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); return objectMapper.readValue(json, clazz); } catch (Exception e) { logger.info("Json转Obj报错:", e); } return null; } }
Java bean实体类(get set省略)
csv使用@JsonProperty来注解csv文件的列名
xml使用@JacksonXmlProperty来注解xml的属性
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; public class CsvItem { @JacksonXmlProperty(localName = "Label") @JsonProperty("Display Name") private String label; @JacksonXmlProperty(localName = "ValueType") @JsonProperty private String valueType; @JacksonXmlProperty(localName = "Editable") @JsonProperty("Editable") private String editable; @JacksonXmlProperty(localName = "Required") @JsonProperty("Required") private String required; }
import java.util.List; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement; @JacksonXmlRootElement(localName = "Page") public class CsvPage { @JacksonXmlElementWrapper(useWrapping = false) @JacksonXmlProperty(localName = "Item") private List<CsvItem> csvItems; public CsvPage() { } public CsvPage(List<CsvItem> csvItems) { this.csvItems = csvItems; } public List<CsvItem> getCsvItems() { return csvItems; } public void setCsvItems(List<CsvItem> csvItems) { this.csvItems = csvItems; } }
注意scv需要设置schema也就是csv文件的列名
public static <T> List<T> toNormalObject(byte[] bytes, Class<T> clazz) throws JsonProcessingException, IOException { CsvSchema schema = CsvSchema.emptySchema().withHeader(); MappingIterator<T> mappingIterator = csvMapper .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) .readerFor(clazz).with(schema).readValues(bytes); return mappingIterator.readAll(); }
xml文件如果需要格式化输出
xmlMapper.setSerializationInclusion(include).writerWithDefaultPrettyPrinter().writeValueAsBytes(object);
writerWithDefaultPrettyPrinter需要依赖
<groupId>org.codehaus.woodstox</groupId> <artifactId>woodstox-core-asl</artifactId>
例子中的xml文件
<Page> <Item> <Label>Account</Label> <ValueType/> <Editable>true</Editable> <Required>true</Required> </Item> <Item> <Label>Outstanding</Label> <ValueType/> <Editable>false</Editable> <Required>false</Required> </Item> </Page>
例子中的csv文件
Display Name,Editable,Required Account,TRUE,TRUE Outstanding,FALSE,FALSE
例子中csv文件有三个属性xml有四个属性,所以xml中<ValueType/>属性为空
由于Jackson处理Json内容比较多
下一篇有时间再详细说明
以上