When you are first starting out with Mule, it is very important to learn the basics, such as how to manipulate the incoming payload.
In this article, I am going to explain how you to transform an incoming payload (JSON) to a Java object.
Most of the work in development revolves around payload transformation, so it is very important to tackle this — especially for beginners.
I will first show the basics, and later on, we will get into the more advanced stuff.
Let's first start by posting a very basic JSON string as payload.
Given the JSON string above, let's now define a transformer component in our flow.
In our case, we are going to use a JSON to Object transformer.
Under the General properties of the JSON to Object transformer component, you can define your desired return class.
java.util.HashMap as the return class for this example.
Once you run the flow above, our JSON string payload is then converted to a Java object
HashMap. You will then be able to access the properties of your payload through
propertyname is defined in the JSON string (i.e.
You can also use other Java Objects such as
Taking It Further
What if you would like to transform the incoming JSON string into a custom Java object?
In order for us to satisfy this, let's first define a custom Java class (
Note: The custom Java class' variables should have the exact same name (case sensitive) as the JSON string's properties. If the names are different, the transformer component will throw an error.
Once this is done, we can then change the return class of the JSON to Object transformer component we defined earlier to our custom class:
Let's try to debug this example.
As you can see, our original payload has been transformed into the custom Java object
We can then try to access the properties of our payload through
propertyname being defined in the custom Java class — i.e.
How about transforming the JSON String into a custom Java object with a custom Java object
Does this also work using the JSON to Object component?
The answer is yes!
Let's try to make our JSON string a little bit more complex.
We now have an additional JSON properties named
If we are going to use the previous custom Java class we defined, the transformer component will throw an
UnrecognizedPropertyException exception since we have not defined any property named
subjects in our Java class.
In order for us to satisfy this condition, let's first start creating another class named
Subject and add the list of
Subject into our
Student class later on.
Subject class should look like this:
After defining our
Subject class, we can then add it into our
Add the following code into
Don't forget to add the
SET methods for the newly added variable subjects.
Let's now test our application and check to see if the payload transformation to our newly defined custom Java class is successful.
As you can see from the image above, our JSON string has been successfully transformed into our new custom Java object!