I have a Custom Java Object class as below:
package com.me;
public class Person {
String firstName;
String lastName;
public String toString(){
return "{firstName=" + this.firstName + ",lastName=" + this.lastName + "}";
}
}
I would like to transform a JSON payload to this Object, then transform it back to JSON. To do this, I use Dataweave and the below Transform Message processor:
%dw 2.0
output application/java
---
{
"firstName": "Mickey",
"lastName": "Mouse",
} as Object {class : "com.me.Person"}
This returns the Object with first and last name updated. Afterwards, I try to transform it back to JSON with the below script:
%dw 2.0
output application/json
---
payload
However, this returns an empty JSON Object
{}
How can I update my Java class in order to get a JSON payload similar to:
{
"firstName": "Mickey",
"lastName": "Mouse"
}
You need to add at least the getter methods for the fields you want in your JSON.
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
After adding these methods, your object will be converted to JSON as you are expecting.
If you can not change your class, you will need to construct JSON in your transform message after you have created the Java Object. Like this
%dw 2.0
output application/json
---
{
"firstName": payload.firstName,
"lastName": payload.lastName,
}