Mule ESB Object to Json Converter Using Jackson Annotations
1. Mule ESB
How to use Jackson in Object to Json converter
Raffaela Vitiello - 2016
2. In this tutorial we will be creating an easy object to json converter using Jackson annotations
in order to have major control on the fields datamapping.
As usual, let’s begin creating the http inbound component to trigger the flow
3. We want to transform this Object to Json:
package com.mulechampion;
import java.io.Serializable;
import org.codehaus.jackson.annotate.JsonProperty;
public class JsonClass implements Serializable{
/**
*
*/
private static final long serialVersionUID = -5645625751838751914L;
@JsonProperty(value="name")
private String fullName;
@JsonProperty(value="surname")
private String fullSurname;
@JsonProperty(value="profession")
private String job;
public JsonClass(String fullName, String fullSurname, String job) {
super();
this.fullName = fullName;
this.fullSurname = fullSurname;
this.job = job;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getFullSurname() {
return fullSurname;
}
public void setFullSurname(String fullSurname) {
this.fullSurname = fullSurname;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
@Override
public String toString() {
return "JsonClass [fullName=" + fullName + ", fullSurname="
+ fullSurname + ", job=" + job + "]";
}
}
4. The problem here is that there’s no automatic field mapping based on the fields name,
resulting in the following error, if we start the application with this flow:
org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "name"
(Class com.mulechampion.JsonClass), not marked as ignorable
To solve this, we will use Jackson annotations in this way:
@JsonProperty(value="name")
private String fullName;
@JsonProperty(value="surname")
private String fullSurname;
@JsonProperty(value="profession")
private String job;
5. If we start now the application we will finally obtain the following output on the console:
HTTP_Listener_Configuration.worker.01]
org.mule.api.processor.LoggerMessageProcessor:
{"name":"Gennaro","surname":"Spagnoli","profession":"programmer"}