2

I read through Camel book, but can't really understand how to differentiate this two, they looks like the same, which both trying to convert a data type to another. Anyone can further elaborate in which situation I should use specific one over another? And any difference between these two?

Data format

http://camel.apache.org/data-format.html

Pseudo example:

from("file://riders/inbox")
.marshal().csv()
.to("activemq:queue:inbox");

Type Converter

http://camel.apache.org/type-converter.html

Pseudo example:

from("file://riders/inbox")
.convertBodyTo(String.class)
.to("activemq:queue:inbox");
Sam YC
  • 10,725
  • 19
  • 102
  • 158

2 Answers2

2

If you want to convert a type to any other type, use a Type Converter. For example, you can convert a Cat class to a Dog class using Type Converter.

Marshal / Unmarshal came from the serializeable school. Basically, you can map any data structure in memory to a stream of bytes (probably to save it in disk, for example). Apache Camel mirrors the same (though they have expanded that to some commonly used formats like XML, HL7 etc). Those are also strings (mostly) or types which can be easily represented as a stream of bytes (protobuf for example) which can be easily serialized.

In Apache Camel, if you notice, if you use marshal/unmarshal, it is not generic. The input or output types are fixed - means you cannot convert from a type to any type. But that is not the case with Type Converter - you can convert a type to any type (either using the default type converters or you have to provide the implementation).

You can think of marshal/unmarshal as a specific case of type conversion where the types are fixed (only Camel guys will provide the implementation usually). As you have seen in your example, marshal().csv() is part of the Camel DSL.

But if you use Type Converter, you are free to add your own logic. That is generic.

Dharman
  • 30,962
  • 25
  • 85
  • 135
SRaj
  • 1,168
  • 1
  • 14
  • 36
1

Camel supports different data formats, in a pluggable way. This means that Camel can marshall or unmarshall a message in a given format. Camel natively supports Avro, JSON, protobuf, JAXB, XmlBeans, XStream, JiBX, SOAP, and so on.

Camel knows expected format and type of endpoints,for this camel looks for a type converter, which can transform message from one type to another.You can even use your own Type Converter like a POJO class.

In the below example .convertBodyTO convert the stream to a string first, we can also change the encoding of the stream by setting the charset parameter.

example -

from("file://riders/inbox")
.convertBodyTo(String.class,"UTF-8")
.to("activemq:queue:inbox");

.marshal().csv() marshels it to csv string format

You can use Dataformat when you have to convert your message to specific data types like JSON,YAML,JAXB, but you cannot use DataFormat to convert your message to user defined data type.

Shubham Chopra
  • 1,678
  • 17
  • 30