简体   繁体   中英

Mule 4: How to transform a Java Custom Object to JSON

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,
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM