将带有JAXB注解的类映射到CSV(或通用格式)

huangapple go评论66阅读模式
英文:

Mapping JAXB Annotated Classes to CSV (or to generic format)

问题

我有一些使用JAXB注解的类,这些类是从某个DTD生成的,它们允许我以相当自动化的方式将对象转换为XML,以及将XML转换为对象。

这些XML被发送到一些由供应商提供给我们的远程服务。然后其他XML被接收回来并解析成我们的领域对象。

应用程序的流程大致如下:

  • 处理领域对象
  • 将其映射到JAXB对象
  • 使用JAXB marshaller将其转换为XML

类似的,将接收到的XML文件转换为JAXB对象,然后转换为领域对象的逆过程也是类似的。

领域对象和JAXB对象之间的映射不是自动的:字段和结构是不同的。因此,其中涉及一些逻辑。

现在,有一个供应商要求我们提供CSV文件而不是XML文件。这是一个问题,因为我们不想复制映射逻辑。因此,我们希望重用这些JAXB对象(以及可能的注解)。

如果可能的话,我们也想避免进行两步处理,比如先生成XML,然后将其转换为CSV(反过来也是一样)。

有没有办法使用JAXB对象(即JAXB注解)"自动"将对象映射到CSV?更明确地说,最好能够保持XML标签的名称作为CSV列的列名。

否则,我们如何以一种较为优雅的方式解决这个问题?

注意:我知道如何将Java类映射到CSV列。我所说的"优雅"是指不重写新的映射类,或者可能不必更改数据映射。例如,使用Jackson-datatype-text中的ObjectMapper可以进行数据转换,但在这种情况下,我必须使用Java对象字段名称,而不能使用在XML中使用的映射字段。

感谢您的支持。

英文:

I've got a certain number of JAXB annotated classes, generated from some DTD, which allow me to transform objects to xml and xml to objects in quite authomatic way.
These xml are sent to some remote services given to us by some suppliers. Then other xmls are received back and parsed into our domain objects.

The applicative process is something like that

  • Process Domain Objects
  • Map them to JAXB Objects
  • Translate them to xml using the jaxb marshaller.

The inverse flow, which translates XML files received to JAXB Objects and then to domain objects is analogous.

The mapping between domain objects and JAXB objects is not authomatic: fields and structure are different. So there's some logic in it.

Now a supplier asked us to provide CSV files instead of XML files. That is a problem because we don't want to duplicate the mapping logic. So we'd like to reuse the JAXB objects (and possibly their annotations).

We would like also to avoid to make a 2 steps process, like generating xml and then translating it to CSV, if possible (and so for the inverse process).

Is there a way to 'automatically' map the objects to CSV using the JAXB Objects (i.e. the JAXB annotations ) ? To be clearer, the top would be being able to mantain the names of the xml tags into the csv columns.

Otherwise how can we solve this is a someway elegant way ?

NB. I know how to map java classes to csv columns. What i mean for 'elegant' is without rewriting new Mapping classes or, possibly, without having to change the data mapping. For exampe with ObjectMapper in Jackson-dqataformat-text is possible to have data conversion, but in that case i must use java objects field names and not mapped fields used in xml

Thanks for support

答案1

得分: 1

以下是翻译好的内容:

这是不可能的。JAXB(Jakarta XML Binding)用于在 XML 和 Java 之间进行映射。它允许将 Java 对象转换为 XML,以及将 XML 转换为 Java 对象。因此,不能使用这个框架来将 Java 对象转换为 CSV。了解更多信息

但是还有一些其他框架支持您的需求,可以将 Java 对象转换为 CSV。opencsv 是在 Java 中处理 CSV 的最佳库。了解更多信息

以下示例与 opencsv 相关。

Person.java

public class Person {
    
    @CsvBindByPosition(position = 0)
    private int id;
    @CsvBindByPosition(position = 1)
    private String name;
    
    public Person(int id, String name) {
        super();
        this.id = id;
        this.name = name;
    }
    
    public int getId() {
        return id;
    }
    public String getName() {
        return name;
    }
}

将人员列表转换为 CSV

try {
    FileWriter writer = new FileWriter("output.csv");
  
    List<Person> listPerson = new ArrayList<Person>();
    listPerson.add(new Person(1, "Test One"));
    listPerson.add(new Person(2, "Test Two"));
  
    ColumnPositionMappingStrategy mappingStrategy = new ColumnPositionMappingStrategy();
    mappingStrategy.setType(Person.class);
  
    StatefulBeanToCsvBuilder<Person> builder = new StatefulBeanToCsvBuilder(writer);
    StatefulBeanToCsv beanWriter = builder.withMappingStrategy(mappingStrategy).build();
  
    beanWriter.write(listPerson);
    writer.close();
            
} catch (Exception e) {
    e.printStackTrace();
}

输出:

1, Test One
2, Test Two

将以下依赖项添加到您的项目中:

  • opencsv
  • commons-beanutils
  • commons-collections
  • commons-lang3
  • commons-logging
英文:

it is not a possible. JAXB (Jakarta XML Binding) facilitate to mapping between xml and java. it allows to convert java object into xml and xml to java object. hence, cannot use this framework for convert java object to CSV. for more info

but some another framework support to your requirement, convert java object to csv. opencsv is a best library for work with csv in java.for more info.

following example is related with opencsv.

Person.java

public class Person {
	
	@CsvBindByPosition(position = 0)
	private int id;
	@CsvBindByPosition(position = 1)
	private String name;
	
	public Person(int id, String name) {
		super();
		this.id = id;
		this.name = name;
	}
	
	public int getId() {
		return id;
	}
	public String getName() {
		return name;
	}
}

convert list of person to csv

try {
    FileWriter writer = new  FileWriter(&quot;output.csv&quot;);
  
    List&lt;Person&gt; listPerson = new ArrayList&lt;Person&gt;();
    listPerson.add(new Person(1, &quot;Test One&quot;));
    listPerson.add(new Person(2, &quot;Test Two&quot;));
  
    ColumnPositionMappingStrategy mappingStrategy=  new ColumnPositionMappingStrategy();
    mappingStrategy.setType(Person.class);
  
    StatefulBeanToCsvBuilder&lt;Person&gt; builder= new StatefulBeanToCsvBuilder(writer);
    StatefulBeanToCsv beanWriter =  builder.withMappingStrategy(mappingStrategy).build();
  
    beanWriter.write(listPerson);
    writer.close();
            
} catch (Exception e) {
    e.printStackTrace();
}

output,

1, Test One
2, Test Two

add the following dependencies into your project,

  • opencsv
  • commons-beanutils
  • commons-collections
  • commons-lang3
  • commons-logging

huangapple
  • 本文由 发表于 2020年8月27日 19:30:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/63615065.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定