...
The line above will exclude fields annotated with @ExcludeAge
when marshalling to JSON.
Configuring field naming policy
Available as of Camel 2.11
The GSON library supports specifying policies and strategies for mapping from json to POJO fields. A common naming convention is to map json fields using lower case with underscores.
We may have this JSON string
Code Block |
---|
{
"id" : 123,
"first_name" : "Donald"
"last_name" : "Duck"
}
|
Which we want to map to a POJO that has getter/setters as
Code Block | ||
---|---|---|
| ||
public class PersonPojo {
private int id;
private String firstName;
private String lastName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
|
Then we can configure the org.apache.camel.component.gson.GsonDataFormat
in a Spring XML files as shown below. Notice we use fieldNamingPolicy
property to set the field mapping. This property is an enum from GSon com.google.gson.FieldNamingPolicy
which has a number of pre defined mappings. If you need full control you can use the property FieldNamingStrategy
and implement a custom com.google.gson.FieldNamingStrategy
where you can control the mapping.
Code Block | ||
---|---|---|
| ||
<!-- define the gson data format, where we configure the data format using the properties -->
<bean id="gson" class="org.apache.camel.component.gson.GsonDataFormat">
<!-- we want to unmarshal to person pojo -->
<property name="unmarshalType" value="org.apache.camel.component.gson.PersonPojo"/>
<!-- we want to map fields to use lower case and underscores -->
<property name="fieldNamingPolicy" value="LOWER_CASE_WITH_UNDERSCORES"/>
</bean>
|
And use it in Camel routes by referring to its bean id as shown:
Code Block | ||
---|---|---|
| ||
<camelContext xmlns="http://camel.apache.org/schema/spring">
<route>
<from uri="direct:inPojo"/>
<marshal ref="gson"/>
</route>
<route>
<from uri="direct:backPojo"/>
<unmarshal ref="gson"/>
</route>
</camelContext>
|
Dependencies for XStream
To use JSON in your camel routes you need to add the a dependency on camel-xstream which implements this data format.
...